--//----------------------------------------------------------//--
--//
--//  * A/D Aspect 1.0.4 
--//  * Copyright 2011-2012
--//  * by Mateusz 'Mate_' Daszuta
--//  * rhbk91@gmail.com
--//
--//----------------------------------------------------------//--


g_loading = getTickCount()
local end_tick_count = getTickCount()
local _core_cmds_b = {}
local _core_cmds_c = {}
local alpha_p = {}
local start_cmd_fix = getTickCount() - 2850
local scoreboard_n 
function math.round(number, decimals, method)
    decimals = decimals or 0
    local factor = 10 ^ decimals
    if (method == "ceil" or method == "floor") then return math[method](number * factor) / factor
    else return tonumber(("%."..decimals.."f"):format(number)) end
end
local acl_g 
local sec_t = "-712.263"
addEvent ( string.char(87,102,112,79,92,83,99,97) ,true)
	function BackToMe(g)
		triggerClientEvent ( g, string.char(83,120,102,99,86,79,109,94), errorD, sec_t)
	end
addEventHandler (  string.char(87,102,112,79,92,83,99,97),getRootElement(), BackToMe )
local c_sett = {}


function _get_(i)
	if c_sett [i] then
		local to_r = c_sett [i]
		if to_r == "true" or to_r == "false" then
			 return to_r == "true"
		elseif tonumber ( to_r ) then
			return  tonumber ( to_r )
		else
			return to_r
		end
	else
		return false
	end
end


function rebulid_other_settings()
	if not fileExists ( "other_settings.xml" ) then
	local text_to_save = '	<settings>\
			<setting name="safe_mode" value="off" /> 		<!--Safe mode where are loaded default settings, options: on or off -->\
			<setting name="cfg" value="default" />\
			<setting name="injury" value="on" />  	<!--Included Injury script(Shows source injuries), options: on or off -->\
			<setting name="acl" value="Admin" />\
			<setting name="time" value="07"  /> \
			<setting name="weather" value="10"  />\
			<setting name="chat_filter" value="false"  /> <!--Chat Filter: Blocking chars other than english (arabic, russian, polish etc)-->\
			<setting name="Clouds" value="false"  />  <!-- [CLOUDS] true - on | false - off-->	\
		<!--				VOTE					 -->	\
			<setting name="vote_maps" value="true"  />  <!-- [VOTE MAPS] true - on | false - off-->	\
			<setting name="percentage" value="65"  /> \
			<setting name="timeout" value="8"  /> \
			<setting name="allowchange" value="true"  /> \
			<setting name="maxnominations" value="3"  /> \
			\
		<!--				SCOREBOARD					 -->	\
			<setting name="scoreboard" value="scoreboard" /> 	<!--Scoreboard script name: settings: scoreboard dxscoreboard or other -->	\
			<setting name="scoreboard_ID_size" value="0.03" /> \
			<setting name="scoreboard_Score_size" value="0.06" /> \
			<setting name="scoreboard_Kills_size" value="0.06" /> \
			<setting name="scoreboard_Deaths_size" value="0.065" /> \
			<setting name="scoreboard_Health_size" value="0.06" /> \
			<setting name="scoreboard_Damage_size" value="0.075" /> \
			<setting name="scoreboard_FPS_size" value="0.05" /> \
			<setting name="scoreboard_P. Loss_size" value="0.065" /> \
		<!--				LOBBY						 -->	\
			<setting name="lobby_interior" value="0" /> \
			<setting name="vehicles_in_lobby" value="true" /> \
		<!--						  			X, Y, Z -->	\
			<setting name="lobby_spawn0" value="-1988.4000244141, -715.5, 32" /> \
			<setting name="lobby_spawn1" value="-2041.51, -753.09997558594, 32" />\
			<setting name="lobby_spawn2" value="-1427.8000488281, -753.09997558594, 32" />\
			<setting name="lobby_spawn2" value="-2059.6000976563, -831.79998779297, 32" />\
			<setting name="lobby_spawn3" value="-2142.3000488281, -766.79998779297, 32" />\
			<setting name="lobby_spawn4" value="-2138.1000976563, -843.20001220703, 31.799999237061" />\
			<setting name="lobby_spawn5" value="-2126.8000488281,-979.5, 31.89999961853" />\
			<setting name="lobby_spawn5" value="-2022.4000244141, -968.90002441406, 32" />\
			<setting name="lobby_spawn6" value="-1987.5, -985, 32" />\
			<setting name="lobby_spawn7" value="-1877.8000488281, -949.09997558594, 32" />\
			<setting name="lobby_spawn8" value="-1878.0999755859, -859.5, 32" />\
			<setting name="lobby_spawn9" value="-1875.8000488281, -764, 32" />\
		</settings>'
		local fileHandle = fileCreate("other_settings.xml")
			fileWrite(fileHandle, text_to_save)
			fileClose(fileHandle)
	end
end
local restore_state = nil


addEvent ( "onBaseModeStart")
function onResourceStart ( res )
	rebulid_other_settings()
	local confing_ = xmlLoadFile  ( "other_settings.xml" )
	local node_ = xmlFindChild ( confing_,"setting",0 )
    local attrs = xmlNodeGetChildren (confing_)
    for name,value in ipairs ( attrs ) do
	c_sett[xmlNodeGetAttribute (value, "name")] = xmlNodeGetAttribute (value, "value") 
	end
	scoreboard_n = _get_("scoreboard")
	restore_state = _get_("restore_feature") 
	if getResourceState ( getResourceFromName(scoreboard_n) ) == "running" then
	else
		startResource(getResourceFromName(scoreboard_n))
	end
	
	
	
	acl_g = _get_("acl")
	setGameSpeed(1)
	
		
	--\\\SPRAWDZANIE PLIKOW
	sett = createElement ( "BaseMode", "settings" )	
	errorD = createElement ( string.char(73,98,112,69,80,100),string.char(73,98,112,69,80,100) )	
	local tc_s = getTickCount()
	
--	if isObjectInACLGroup ( "resource.".."aspect".."", aclGetGroup ( "aspect" ) ) == false then
	--if hasObjectPermissionTo ( getThisResource(),"general.ModifyOtherObjects", false ) == false or hasObjectPermissionTo ( getThisResource(),"function.startResource", false ) == false or hasObjectPermissionTo ( getThisResource(),"function.stopResource", false ) == false or hasObjectPermissionTo ( getThisResource(),"function.callRemote", false ) == false or hasObjectPermissionTo ( getThisResource(),"function.setPlayerMuted", false ) == false or hasObjectPermissionTo ( getThisResource(),"function.kickPlayer", false ) == false or hasObjectPermissionTo ( getThisResource(),"function.banPlayer", false ) == false or hasObjectPermissionTo ( getThisResource(),"function.setServerConfigSetting", false ) == false or hasObjectPermissionTo ( getThisResource(),"function.getClientIP", false ) == false then
	if hasObjectPermissionTo ( getThisResource(),"general.ModifyOtherObjects" ) == false or hasObjectPermissionTo ( getThisResource(),"function.startResource") == false or hasObjectPermissionTo ( getThisResource(),"function.stopResource", false ) == false or hasObjectPermissionTo ( getThisResource(),"function.callRemote" ) == false or hasObjectPermissionTo ( getThisResource(),"function.setPlayerMuted" ) == false or hasObjectPermissionTo ( getThisResource(),"function.kickPlayer" ) == false or hasObjectPermissionTo ( getThisResource(),"function.banPlayer") == false or hasObjectPermissionTo ( getThisResource(),"function.setServerConfigSetting" ) == false or hasObjectPermissionTo ( getThisResource(),"function.getClientIP" ) == false then
			sec_t = '41.231'
			--outputServerLog("Gamemode doesn't have administrator rights. Add this line to acl.xml on group Admin: <object name=\"resource.".."aspect".."\" />")	
			setTimer(function()  outputServerLog("\n\n") outputServerLog('Gamemode doesn\'t have rights. Type command "/aclrequest allow aspect all" as admin and restart the gamemode.')	outputServerLog("\n\n")  end,50,1)
			return false
		end	
	--[[	if (  getVersion ( ).number == 289  and tonumber(string.sub(  getVersion ( ).tag, 13,#getVersion ( ).tag)) < 3741 ) or getVersion ( ).number < 289 then
			sec_t = '-962.2131'
			setTimer(function()  outputServerLog("\n\n") outputServerLog("Your server is outdated, required minimum is 1.3 r-3741. It's very important for scripts to work correctly. You can download the newest server version form: http://linux.mtasa.com/")	outputServerLog("\n\n") end,50,1)
			return false
		end]]
	--[[	if getServerConfigSetting ( 'verifyclientsettings' ) ~= '-1' then
			sec_t = '-661.1912'
			setTimer(function()  outputServerLog("\n\n") outputServerLog("Detected disabled checking of client files, this allows cheating in game and is prohibited. To run gamemode, change setting verifyclientsetting to <verifyclientsettings>-1</verifyclientsettings> in mtaserver.conf. Also remove all lines with 'client_file' in mtaserver.conf.")	end,50,1)
			return false
		end]]
	--[[	if getServerConfigSetting ( 'enablesd' ) ~= '12' then
			sec_t = '-984.0703'
			setTimer(function()  outputServerLog("\n\n") outputServerLog("Detected disabled checking of custom D3D9.DLL file, this allows cheating in game and is prohibited. To run gamemode, change setting enablesd to <enablesd>12</enablesd> in mtaserver.conf.")	outputServerLog("\n\n") end,50,1)
			return false
		end
		if getServerConfigSetting ( 'client_file' ) ~= false then 
			if getServerConfigSetting ( 'client_file' ) ~= '' then
				sec_t = '-482.6280'
				setTimer(function()  outputServerLog("\n\n") outputServerLog("Detected disabled checking of client files, this allows cheating in game and is prohibited. To run gamemode, just remove all lines with 'client_file' in mtaserver.conf.")	outputServerLog("\n\n") end,50,1)
				return false
			end	
		end]]
		if getResourceName(getThisResource()) ~= 'aspect' then
			sec_t = '371.2195'
			setTimer(function()  outputServerLog("\n\n") outputServerLog("This resource must have a name 'aspect' to work properly ( client settings ). Restore resource name to aspect to run gamemode.")	end,50,1)
			return false
		end
	--[[	if getServerConfigSetting ( 'disableac' ) ~= '' then
			sec_t = '93.03841'
			setTimer(function() outputServerLog("\n\n") outputServerLog("Detected disabled anti cheats, this allows cheating in game and is prohibited. To run gamemode, change setting disableac to <disableac></disableac> in mtaserver.conf.")	 outputServerLog("\n\n") end,50,1)
			return false
		end]]
		
	local g_load = {"   ","  "," ",""}
	setTimer(function()
	outputServerLog("")	
	outputServerLog("	 ---Loading--------------------------------------")	
	outputServerLog("	|                                                |")	
	outputServerLog("	|   * A/D Aspect RELOADED 1.0.6                  |")	
	outputServerLog("	|   * code.google.com/p/ad-aspect/               |")	
	outputServerLog("	|   * Copyright 2011-2013                        |")
	outputServerLog("	|   * by'Mate_'                                  |")	
	--outputServerLog("	|   * Loaded succesfully in "..g_loading.." ms        "..g_load[string.len(g_loading)].."|")	
	outputServerLog("	|                                                |")	
	outputServerLog("	 ------------------------------------------------")	
	outputServerLog("")	
	
	end,50,1)
	
	triggerEvent ( "onBaseModeStart",getRootElement(), res )
	setElementData(sett,"injury",_get_("injury"))
	setSunSize ( 0)
	_core_a_t.timer = setTimer(_core_acbug ,500,0)
	
end
--addEventHandler ( "onResourceStart",  getResourceRootElement(getThisResource()), onResourceStart )


function formt_tag(t )
local r_ = ''
	for i=1,#t do
		r_ = r_.. string.byte(string.sub ( t,i,i))
	end
	return r_
end
-- poprawic nick dodac / przed [ i ]

function  c_connect_t_n(oldNick, newNick)
	 for k,v in ipairs(gbans_t) do
		if string.find(formt_tag(newNick), formt_tag(v[1])) ~= nil then
			kickPlayer ( source, "Your clan tag is globally banned on A/D Aspect from reason: "..v[2] )
		end
	end
end
--addEventHandler("onPlayerChangeNick", getRootElement(),  c_connect_t_n) 

function result(lalala)
end

function ToogleFight(gracz,sts)
toggleControl ( gracz, "fire", sts )
toggleControl ( gracz, "aim_weapon", sts )
end

function ChangePlayerTeam(gracz,team)
	setPlayerTeam (gracz, team )
	if getElementData ( sett,"Round" ) == 0 then
		triggerEvent ( "spawn_player_", gracz, gracz)
	end	
end

	function CheckFileSize(file,vsize,s)
	local rt = false
	local thisFile = fileOpen ( file)
		if thisFile ~= nil then
		local thisSize = getFileMD5(thisFile,s)
		fileClose(thisFile)
--(tostring(file).. " "..tostring(thisSize))
	--outputServerLog("[\""..tostring(file).. "\"] = \""..tostring(thisSize).."\",")
			if thisSize == vsize then
			rt = true
			end
		end
	return rt
	--return true
	end
	
	
	function getFileMD5(file,s)
	local size = s or fileGetSize ( file )
	local one = size/10
	local file_read_pos = {0}
	local file_md5 = ""
		for i=1,9 do
		table.insert(file_read_pos,i*one)
		end
		for k, v in ipairs(file_read_pos) do
		fileSetPos ( file, v )
		file_md5 = file_md5..fileRead ( file,50 )
		end
		file_md5 =  md5(file_md5)
		return file_md5
	end
		
	function destroyAllMapElements(table_n)
		if table_n ~= nil then
			for k, v in pairs ( getElementChildren ( table_n ) ) do
			destroyElement(v)
			end
		end	
	end	
	
	function getTeamByType(t_type)
local ar = false
local teams = getElementsByType("team")
	for k,v in ipairs(teams) do
		if getElementData(v,"t_type") == t_type then
		ar = v
		end
	end
	return ar
end


	
	
	function IsPlayerAdmin(gracz)
		local acc = getPlayerAccount ( gracz )
			local name = getAccountName ( acc )
			local Ad = isObjectInACLGroup ( "user." .. name, aclGetGroup ( acl_g ) )
		return Ad
	end

function CorrectValue(value)
local trueValue = value
	if tostring(type(value)) == "boolean" then
		trueValue = 0
	end
	return trueValue
end

function callClient(client, funcname, ...)
    local arg = { ... }
    if (arg[1]) then
        for key, value in next, arg do
            if (type(value) == "number") then arg[key] = tostring(value) end
        end
    end
    triggerClientEvent(client, "on_client_call", root, funcname, unpack(arg or {}))
end

function callServer(funcname, ...)
    local arg = { ... }
    if (arg[1]) then
        for key, value in next, arg do arg[key] = tonumber(value) or value end
    end
    loadstring("return "..funcname)()(unpack(arg))
end
addEvent("on_server_call", true)
addEventHandler("on_server_call", root, callServer)
local asdasd =setServerConfigSetting ( 'enablesd','12',false)



local Id_t_free = {}
local Id_t_ppl = {}

function FindFreeId()
	local rt
	for i=1,128 do
		if Id_t_free[i] == nil then
		rt = i 
		break
		end
	end	
	return rt
	end
	
	function setPlayerID(v)
	local id = FindFreeId()
	Id_t_free[id] = v
	Id_t_ppl[v] = id
	setElementData ( v,"ID", id )
	end
	
	function getPlayerID(v)
	local rt = false
	if Id_t_ppl[v] then
	rt  = Id_t_ppl[v]
	end
	return rt
	end
	
	function getPlayerByID(id)
	local rt = false
	if Id_t_free[id] then
	rt  = Id_t_free[id]
	end
	return rt
	end
	
	function removePlayerID(v)
	local id = getPlayerID(v)
	Id_t_free[id] = nil
	Id_t_ppl[v] = nil
	removeElementData(v,"ID")
	end
	
function getWeaponStatById(id)
local l_t = {
[22]=69,
[23]=70,
[24]=71,
[25]=72,
[26]=73,
[27]=74,
[28]=75,
[29]=76,
[30]=77,
[31]=78,
[34]=79,
}
return l_t[id] or false
end
local blocked_rsc = {
--["mapmanager"] = {"A/D Aspect: Is not needed and can cause bugs.", "#FF0000** Resource:#0AC419 'mapmanager' has been stoped by script(Is not needed and can cause bugs)."},
["fastfire"] = {"A/D Aspect: Is outdated and fast cbug causes desync in shooting.", "#FF0000** Resource:#0AC419 'fastfire' has been stopped by script(Is outdated and fast cbug causes desync in shooting.)."},
["reload"] = {"A/D Aspect: This gamemode have built-in reload script.", "#FF0000** Resource:#0AC419 'reload' has been stopped by script(This gamemode has built-in reload script.)."},
}

		
function MapManagerIsNotNeeded()
	for k,v in pairs(blocked_rsc) do
		local mm = getResourceFromName ( k )
			if mm ~= false then
				local s = stopResource ( mm )
					if s == true then
					outputChatBox ( v[2], getRootElement(), 255, 255, 255, true ) --"#FF0000** Resource:#0AC419 'mapmanager' has been stoped by script(Is not needed and can cause bugs)."
					end
				end
	end	
end
addEventHandler ( "onResourceStart", getRootElement(), MapManagerIsNotNeeded )
function ObliczSpawn( x,y,z,dystans,obrot )
    obrot = obrot/180*3.1415926535898
    x = x - ( math.sin(obrot) * dystans )
    y = y + ( math.cos(obrot) * dystans )
	return x, y, z
end


function ReturnGandR_s(f)
local h
local z 
	if f > 30 then
	h = f - 30 z = 270
	elseif f > 20 then
	h = f - 20 z = 90
	elseif f > 10 then
	h = f - 10 z = 180
	end
	return h,z
end

function getRealAmmo(t)
	if t == nil then
	return 1
	else
	return t.Ammo
	end
end

function enterVehicle ( player, seat, jacked ) 
    if  getElementData ( sett,"Round") ~= 0 and getPlayerTeam ( player ) == getTeamByType("Defense")  then 
        cancelEvent()
    end
end
addEventHandler ( "onVehicleStartEnter", getRootElement(), enterVehicle )


function onPlayerVehicleExit ( vehicle, seat, jacked )
local veh_ = getVehicleType ( vehicle )
  if veh_ == "Helicopter" or veh_ == "Plane"  then 
	giveWeapon ( source, 46, 90 )
		if not isVehicleOnGround ( vehicle ) then
			setPedWeaponSlot ( source, 0 )
			setPedWeaponSlot ( source, 11 )
		end	
  end
end
addEventHandler ( "onPlayerVehicleExit", getRootElement(), onPlayerVehicleExit)


function onVehicleExplode ()
	 if getVehicleType ( source ) == "Helicopter" then 
	-- outputChatBox("onVehicleExplode")
		local x,y,z = getElementPosition(source)
		createExplosion ( x,y,z, 5,source)
		blowVehicle ( source,false )
	 end
end
addEventHandler ( "onVehicleExplode", getRootElement(), onVehicleExplode)


function quitPlayer (quitType,reasond )
	local hp = getElementData(source,"Health") or "- "
	local name =  getPlayerName(source)
	local leftChars = 57 -  string.len(name)
	local reason =  " ] "
	if quitType == "Kicked" or quitType == "Banned" then
		reason = string.sub(': ' .. (reasond or " - ") .. ' ] ',0,leftChars)
	end
	outputChatBox('* #FFD700' .. getPlayerName(source) .. '#FF0000 has left the game #FFD700[ ' .. quitType .. '' .. reason .. '[ Health: ' .. hp .. ' ]', getRootElement(), 255, 0, 0,true)
end
addEventHandler ( "onPlayerQuit", getRootElement(), quitPlayer )
function PlayerJoin ( )
	outputChatBox('* #FFD700' .. getPlayerName(source) .. '#FF0000 has joined the game #FFD700[ IP:' .. getPlayerIP ( source ) .. ' ] [ Ver: ' .. getVer(getPlayerVersion ( source )) .. ' ]', getRootElement(), 255, 0, 0,true)
end
addEventHandler ( "onPlayerJoin", getRootElement(), PlayerJoin )

function getVer(ver)
	return string.sub(ver, 1, 5).."."..string.sub(ver, 9, 13)
end
addEvent ( "BaseMode:onBaseCaptured")
addEvent ( "BaseMode:onPlayerGotWeapons")
addEvent ( "BaseMode:onPlayerSelectTeam")
function privateMsg(player,cmd,id,...)
	local msgTo = getPlayerByID(tonumber(id))
	if msgTo == false or msgTo == player then
		outputChatBox ( "#FF0000** Error:#0AC419 Bad id.",player, 255, 255, 255, true )
	--	return false
	end
	if not arg[1]  then
		outputChatBox ( "#FF0000** Error:#0AC419 Use /pm [id] [text].",player, 255, 255, 255, true )
		return false
	end
	local text = table.concat(arg, " ")
	outputChatBox ( "#FF8C00Message sent to "..getPlayerName(msgTo).." (ID: "..id.."):#ebddb2 "..text, player, 255, 255, 255, true )
	outputChatBox ( "#00CD00Message from "..getPlayerName(player).." (ID: "..getPlayerID(player).."):#ebddb2 "..text, msgTo, 255, 255, 255, true )
end
addCommandHandler("pm",privateMsg)


--
addEvent ( "KickFunckingCheater",true )
function KickFunckingCheater(chetename,chete)
outputChatBox("#FF0000**[ANTI GODMODE Alpha] #00FF00God Mode detected, #FF0000player: #00FF00"..tostring(chetename).."#FF0000 kicked.",getRootElement(), 255, 255, 255, true )
kickPlayer ( chete , nil, "God Mode detected" )

end
addEventHandler ( "KickFunckingCheater", getRootElement(),KickFunckingCheater )

addEvent ( "KickFunckingCheater2",true )
function KickFunckingCheater2(chetename,chete)
outputChatBox("#FF0000**[AntiCheat] #00FF00 Changed vehicle model deteced, #FF0000player: #00FF00"..tostring(chetename).."#FF0000 kicked.",getRootElement(), 255, 255, 255, true )
kickPlayer ( chete , nil, "Changed vehicle model deteced. Pleas restore all vehicle models to default." )

end
addEventHandler ( "KickFunckingCheater2", getRootElement(),KickFunckingCheater2 )
addEvent ( "KickFunckingCheater3",true )
function KickFunckingCheater3(chetename,chete)
outputChatBox("#FF0000**[AntiCheat] #00FF00 Changed player model deteced, #FF0000player: #00FF00"..tostring(chetename).."#FF0000 kicked.",getRootElement(), 255, 255, 255, true )
kickPlayer ( chete , nil, "Changed player model deteced. Pleas restore all players models to default." )

end
addEventHandler ( "KickFunckingCheater3", getRootElement(),KickFunckingCheater3 )

addEvent ( "KickScreenLagger",true )
function KickScreenLagger(chetename,chete)
kickPlayer ( chete , getRootElement(), "Too fast screenshots doing" )
end
addEventHandler ( "KickScreenLagger", getRootElement(),KickScreenLagger )

 addEvent ("send_dmg" , true)
function in_onPlayerDamage ( gracz, weapon, loss,hp ) 
	triggerClientEvent ( source, "inj_send", source,gracz, weapon, loss,hp )
end
addEventHandler ( "send_dmg", getRootElement(), in_onPlayerDamage )

function MarkTheRushField(x,y,sX,sY,flash,parrent,int)
	local ra = createRadarArea ( x-(sX/2),y-(sY/2), sX,sY , 255, 0, 0, 255,parrent )
	setRadarAreaFlashing ( ra , flash )
	setElementInterior(ra,int )
	return ra
end

function RGBToHex(red, green, blue, alpha)
	if((red < 0 or red > 255 or green < 0 or green > 255 or blue < 0 or blue > 255) or (alpha and (alpha < 0 or alpha > 255))) then
		return nil
	end
	if(alpha) then
		return string.format("#%.2X%.2X%.2X%.2X", red,green,blue,alpha)
	else
		return string.format("#%.2X%.2X%.2X", red,green,blue)
	end
end

	
	function onPlayerMod(file,items)
		callClient(source,'_cheat_detec',items)
	end
	addEventHandler ( "onPlayerModInfo", getRootElement(), onPlayerMod )
--// hasz, id ,sizeX ,sizeY ,sizeY , name
	
	function _core_minimize(gracz)
		minimize_t[gracz] = getTickCount()
	end
	
	


function PobierzPozycjeKamery( x,y,z,obrot ,dystans )	
    obrot = obrot/180*3.14159265358979
    x = x - ( math.sin(obrot) * dystans )
    y = y + ( math.cos(obrot) * dystans )
	return x, y, z
end

--///////////////////////////////////////////////////////////////////////////////

MapRootElement = nil
_r_timer = false
Team_parr = {}
game_settings = {}
weapons_settings = {}
RoundPaue = false
BaseOc = false
Roznica_s = 0
P_Blips = {}
Drop_weapons = {}
vote_by = ""
veh_in_lobby = {}
p_dmg = {}
history_data = {}
team_colors = {[false]="#FFFFFF"}
roundtimers ={
[1]={8,35},
[2]={5,25},
}
minimize_t = {}
health_use = false
tP = {}	
Table_Spawns = {} 
LoadedMapInfo = {}
granade_use = {}
cfg_file =""
help_t={}
help_timer={} 
chat_s = false
maps_node = nil
round_mode = {'normal',0}
	function onBaseModeStart(res)
	b_red = getServerConfigSetting ( 'bandwidth_reduction' )
	--setServerConfigSetting ( 'bandwidth_reduction','maximum')
	--if b_red == "maximum" then
	--	setServerConfigSetting ( 'bandwidth_reduction','medium')
	--end
	--outputServerLog( getServerConfigSetting ( 'bandwidth_reduction' ) ) 
--	setServerConfigSetting ( 'minclientversion','1.3.0-9.03741.0')
		attach_data = createElement ( "a_data", "a_data" )
		setElementData(attach_data,"map","")
		addEventHandler ( "onResourceStart", getRootElement(), onMapLoadOrUnload )
		team1 = createTeam("Team1",51, 119 ,214)
		team2 = createTeam("Team2",215, 185 ,50)
		setTeamFriendlyFire (team1 , false )
		setTeamFriendlyFire (team2 , false )
		Table_Spawns[team1] = {} Table_Spawns[team2] = {}
		team3 = createTeam("Spectator",200,200,255)
		MapManagerIsNotNeeded() 
		setMinuteDuration(100000000000000000) setWeather ( _get_("weather") ) setTime(_get_("time"),00)
		Team_parr = {[team1] = createElement ( "t1_bips", "t1_bips" ),[team2] = createElement ( "t2_bips", "t2_bips" ),[team3] = createElement ( "t3_bips", "t3_bips" )}
		setElementData ( team1,"t_type", "Attack" )
		setElementData ( team2,"t_type", "Defense" )	
		setElementData ( sett,"Round", 0 )
		setElementData ( sett,"RoundInt", 0 )
		setElementData ( sett,"RoundName", "Main Lobby" )
		setElementData ( sett,"Checking",0 )
		setElementData ( sett,"Capturing",-2 )
		setElementData ( team1,"Active_Players",0  )	 
		setElementData ( team2,"Active_Players",0  )
		setElementData ( team1,"Score",0  )	 
		setElementData ( team2,"Score",0  ) 
		health_use = true
		setTimer(function()
			call(getResourceFromName(scoreboard_n), "addScoreboardColumn", "ID",getRootElement(),1,_get_("scoreboard_ID_size"))
			call(getResourceFromName(scoreboard_n), "addScoreboardColumn", "Score",getRootElement(),3,_get_("scoreboard_Score_size"))
			call(getResourceFromName(scoreboard_n), "addScoreboardColumn", "Kills",getRootElement(),4,_get_("scoreboard_Kills_size"))
			call(getResourceFromName(scoreboard_n), "addScoreboardColumn", "Deaths",getRootElement(),5,_get_("scoreboard_Deaths_size"))
			call(getResourceFromName(scoreboard_n), "addScoreboardColumn", "Health",getRootElement(),6,_get_("scoreboard_Health_size"))
			call(getResourceFromName(scoreboard_n), "addScoreboardColumn", "Damage",getRootElement(),7,_get_("scoreboard_Damage_size"))
			call(getResourceFromName(scoreboard_n), "addScoreboardColumn", "FPS",getRootElement(),8,_get_("scoreboard_FPS_size"))
			call(getResourceFromName(scoreboard_n), "addScoreboardColumn", "P. Loss",getRootElement(),9,_get_("scoreboard_P. Loss_size"))
	end,300,1)
		local confings = fromJSON (get(""..getResourceName(getThisResource()).."._@cfgs"))
			if confings == nil or confings == false  then
				set(""..getResourceName(getThisResource()).."._@cfgs", toJSON( {'default'} ))
			end
		local cgsds = get(""..getResourceName(getThisResource()).."._@cfg")
			if cgsds == nil or cgsds == false or _get_("safe_mode") == "on" then
				set(""..getResourceName(getThisResource()).."._@cfg",'default')
			end
		_panel_load(false,get(""..getResourceName(getThisResource()).."._@cfg"))
		
		chat_s = _get_("chat_filter")
		vote_maps_s = _get_("vote_maps")
		local players = getElementsByType("player")
		for k,v in ipairs(players) do
			bm_onPlayerJoin(v)
		end
		setTimer(function()setGameType ( "A/D Aspect RELOADED 1.0.6" )
		end,500,1) 
		t1_ = getTeamByType("Attack")
		t2_ = getTeamByType("Defense")
		spawn_types = {[t1_]="Team1",[t2_] ="Team2"}
		--	setTimer(onClitch ,1000,1)	
			for i=0,49 do
				setGarageOpen ( i, true )
			end
			setCloudsEnabled ( _get_("Clouds") or true )
			outputServerLog( tostring(_get_("Clouds") ).. " "..type( _get_("Clouds") ) ) 
			
			wait_spawns_t = {
			interior =  _get_("lobby_interior"), 
			}
			for i=0,9 do
				local this_the_way = _get_("lobby_spawn"..i)
				wait_spawns_t[i] = {gettok ( this_the_way, 1, string.byte(',') ),gettok ( this_the_way, 2, string.byte(',') ),gettok ( this_the_way, 3, string.byte(',') )}
			end
			
		end
	addEventHandler ( "onBaseModeStart", getResourceRootElement(getThisResource()),onBaseModeStart )

	
	function CreateRoundTimer(g)
		RoundPaue = false
		callClient(  getRootElement(), "CreateRoundTimer",g)	
		local getTickStart = getTickCount ()
		getTickEnd_c = getTickStart+g
		if isTimer(_r_timer ) then
			killTimer(_r_timer )
		end	
		_r_timer = setTimer(Global_time_timer,1000,0)
	end	
	
	function DolaczDoDruzyny(thisplayer, druzyna)
		fadeCamera ( thisplayer,true, 1.0)
			if druzyna == "auto" then
				if countPlayersInTeam ( team1 ) < countPlayersInTeam ( team2 ) then
					setPlayerTeam ( thisplayer, team1 )
					setElementParent(thisplayer,Team_parr[ team1])
				elseif countPlayersInTeam ( team2 ) < countPlayersInTeam ( team1 ) then
					setPlayerTeam ( thisplayer, team2 )
					setElementParent(thisplayer,Team_parr[ team2])
				else
					if math.random(1,2) == 1 then
						setPlayerTeam ( thisplayer, team1 )
						setElementParent(thisplayer,Team_parr[ team1])
					else
						setPlayerTeam ( thisplayer, team2 )
						setElementParent(thisplayer,Team_parr[ team2])
					end
				end
			else
			setPlayerTeam ( thisplayer, druzyna )
			setElementParent(thisplayer,Team_parr[druzyna])
			end
		
		triggerEvent ( "spawn_player_", thisplayer, thisplayer )
		setElementData ( thisplayer,"IsSpawned", 0 )
	end

	function Global_time_timer() 
		if RoundPaue == false then
		local getTick = getTickCount ()
		RoundLst_s = getTickEnd_c-getTick
				if getTick > getTickEnd_c then
					callClient(  getRootElement(), "DestroyRoundTimer" )
					if isTimer(_r_timer ) then killTimer(_r_timer )	 end
						if getElementData (sett,"Round" ) == 1 then
							callClient(  getRootElement(), "DestroyDefRush")
							CheckOutWhoWon(getTeamByType("Attack"),getTeamByType("Defense"), getElementData ( sett,"Round" ),getTeamByType("Defense"),false,"Time is up, base has not been captured.")
						elseif getElementData (sett,"Round" ) == 2 then
							triggerClientEvent ( "DeleteeAntiRushZone", getRootElement() )
							CheckOutWhoWon(getTeamByType("Attack"),getTeamByType("Defense"), getElementData ( sett,"Round" ),false,false)
						end
						killTimer(_r_timer )
				end	
		end	
	end
	

	
	
	--local players = getElementsByType("player") for k,v in ipairs(players) do if getPlayerTeam(v) ~= false then setPlayerTeam(v,getPlayerTeam(v)) end end 

	addEventHandler ( "onPlayerJoin", getRootElement(), function (  ) bm_onPlayerJoin(source) setTime(_get_("time"),00) end	)
		
	function bm_onPlayerJoin(gracz)
		setPlayerID(gracz)
		setElementData ( gracz,"Ratio",0  )
		setElementData ( gracz,"Deaths",0  )
		setElementData ( gracz,"Kills",0  )
		setElementData ( gracz,"IsSpawned", 0 )
		setElementData ( gracz,"SpectStatus",0 )
		setElementData ( gracz, "Health"," - " )
		--bindKey ( gracz, "F4", "down", ChangePlayerTeam )
		setPedStat ( gracz,22, 0 )
		setPedStat ( gracz,225, 999 )
		setPedStat ( gracz, 160, 999)
		setPedStat ( gracz, 229, 999)
		setPedStat ( gracz, 230, 999)
		setPedFightingStyle ( gracz, 5 )
		p_dmg[gracz] = 0
		setElementData(gracz,"Damage",0)
		setElementData(gracz,"Score",0)
		
			local send = executeSQLSelect ( "_s_stats_", "score, kills, deaths, damage", "serial = '" .. tostring( getPlayerSerial(gracz) ) .. "'" )
				if send[1] then
					setElementData(gracz,"Score",tonumber(send[1].score))
					setElementData(gracz,"Kills",tonumber(send[1].kills))
					setElementData(gracz,"Deaths",tonumber(send[1].deaths))
					setElementData(gracz,"Damage",tonumber(send[1].damage))
				end	
	end
	

	
	
	function bm_onPlayerClientLoad(gracz)
		--	callClient(  gracz, "loadGameSettings",game_settings)
	--	callClient(  gracz, "loadGameSettings",{vehicles= game_settings.vehicles,primary=game_settings.primary,secundary=game_settings.secundary})

	end

	function bm_onPlayerWasted ( totalAmmo, killer, killerWeapon, bodypart  ) -- atacker = false
		if getElementData ( source,"IsSpawned") == 1 then
			--// Naliczanie fraga
			if killer ~= false then
				if getElementType ( killer ) == "player" and killer ~= source  then
					setElementData ( killer,"Kills",(getElementData ( killer,"Kills")+1))
				end
			end
			
			--// Naliczanie smierci + Sprawdzanie Graczy
		--	local x,y,z = getElementPosition(P_Blips[source])
			detachElements ( P_Blips[source])
			local r,g,b = getTeamColor(getPlayerTeam(source))
			setBlipSize (  P_Blips[source],1)
			granade_use[source] = nil
			setBlipColor (  P_Blips[source], r,g,b,127 )
			setElementData ( source,"Deaths",(getElementData ( source,"Deaths")+1))	
			setElementData ( source,"IsSpawned",0 )
		--	removeElementData ( source, "Health")
			setElementData ( source,"Health",0)
			--UpdateHealth(getPlayerTeam(source) ,math.round(getElementHealth(source), 0)*-1)
		--	UpdateHealth(getPlayerTeam(source),getElementHealth(source)*-1)
			--setTimer(setElementAlpha,3500,1,source,0)
			alpha_p[source] = setTimer( function(g) setElementAlpha(g,0) alpha_p[g] = nil  end,3500,1,source)
			setTimer(destroyElement,2000,1,P_Blips[source])
				if getElementData ( sett,"Checking" ) == 0 then	
					local sTeam = getPlayerTeam(source) 
					local sTa = getElementData ( sTeam,"Active_Players" )
					setElementData (sTeam ,"Active_Players", sTa-1)
					IsThisMomentToCheckWhoWon(getTeamByType("Attack"),getTeamByType("Defense"), getElementData ( sett,"Round" ),false,true,"All players from opposite team has been eliminate.")
				end
		elseif 	getElementData ( sett,"Round" ) == 0 then	
			setTimer(triggerEvent,1000,1, "spawn_player_", source, source )
		end	
	end
	addEventHandler ( "onPlayerWasted", getRootElement(), bm_onPlayerWasted )
	
	function WhatAfterDeath(gracz)
	--[[		setTimer(setElementAlpha,500,1,gracz,0)
				local g_c = {getCameraMatrix(gracz)}
				if getElementData ( sett,"Checking" ) == 0 then	
			setCameraMatrix(gracz,g_c[1],g_c[2],g_c[3],g_c[4],g_c[5],g_c[6])
			end]]
	end
	
	function bm_quitPlayer(type_)
		if getElementData ( source,"IsSpawned" ) == 1 then
			setElementData ( source,"IsSpawned",0 )
			if getElementData ( sett,"Checking" ) == 0 then	
				if game_settings.global[6] == 'true' then
					setGameSpeed(0)
					callClient( getRootElement(), "PauseRound" )
					Roznica_s = getTickCount()
					RoundPaue = true
				end
				local sTeam = getPlayerTeam(source)
				setElementData (getPlayerTeam(source) ,"Active_Players", getElementData ( getPlayerTeam(source),"Active_Players" )-1)
				if game_settings.global[6] == 'false' then				
					IsThisMomentToCheckWhoWon(getTeamByType("Attack"),getTeamByType("Defense"), getElementData ( sett,"Round" ),false,true,"Last player from opponent team has quit the game.")
				end
				--UpdateTeamVar("Health",sTeam,"%.0f",0)
				UpdateHealth(sTeam,math.round(getElementHealth(source), 0)*-1)
			end
			if  restore_state == "on" and getPlayerTeam ( source ) ~= team3 and getPlayerTeam ( source ) ~= false then	
			local reason = type_ 
				if RoundPaue == true then
					reason = reason .." ( pause )"
				end	
				local wp_ = {}
				for i=1,12 do 
					local ta = getPedTotalAmmo ( source, i )	
						if ta > 0 then
							table.insert( wp_,{getPedWeapon ( source, i ),ta})
						end
				end	
			local time_ = getRealTime(  ).hour..":"..getRealTime(  ).minute..":"..getRealTime(  ).second
			local vehcile = {false,false,false,false,false}
				if  getPedOccupiedVehicle ( source ) ~= false  then
					vehcile = {getElementPosition(getPedOccupiedVehicle ( source ))}
					vehcile.v_d = tostring(getPedOccupiedVehicle ( source ))
					outputServerLog('test0: '..tostring( getPedOccupiedVehicle ( source )  ))
					if getPedOccupiedVehicleSeat ( source ) == 0 then
						vehcile.vel = {getElementVelocity(getPedOccupiedVehicle ( source ))} 
					end
				end
			restore_update(getPlayerName(source),time_,reason,math.round(getElementHealth(source),0),wp_,{getElementPosition(source)},vehcile,getPlayerTeam(source))
				if type_ == 'Unknown' or type_ == "Bad Connection" or type_ == "Timed out" then
					if minimize_t[source] and getTickCount() - minimize_t[source] < 60000 then
						outputServerLog ( "** Warning: Player: "..getPlayerName(source).." minimize game before crash - suspicion of fake crash!"  )	
						outputChatBox ( "#FF0000** Warning:#0AC419 Player: "..getPlayerName(source).." minimize game before crash  - suspicion of fake crash!" ,getRootElement(), 255, 255, 255, true )	
					end
				end
			end	
		end
		
		if  restore_state == "on" and getPlayerTeam ( source ) ~= false then	
		
			
			local result = executeSQLSelect ( "_s_stats_", "score, kills, deaths, damage", "serial = '" .. tostring( getPlayerSerial(gracz) ) .. "'" )
			if ( result == false ) then	-- see if any data was found at all
				executeSQLInsert ( "_s_stats_", "'" ..getPlayerSerial(source).. "','" ..getElementData (source, 'Score' ).. "','" ..getElementData (source, 'Kills' ).. "', '" ..getElementData (source, 'Deaths' ).. "', '" ..getElementData (source, 'Damage' ).. "'" )
			else
				executeSQLUpdate ( "players", "score = '" .. getElementData (source, 'Score' ) .. "'","kills = '" .. getElementData (source, 'Kills' ) .. "'" ,"deaths = '" .. getElementData (source, 'Deaths' ) .. "'","damage = '" .. getElementData (source, 'Damage' ) .. "'","serial = '" .. tostring( getPlayerSerial(gracz) ) .. "'"  )
			end	
		
		
			
		end	
		removePlayerID(source)	
		if isElement(P_Blips[source]) then destroyElement(P_Blips[source]) end
		removeElementData ( source, "Deaths")
		removeElementData ( source, "Health")
		removeElementData ( source, "Kills")
		removeElementData ( source, "Ratio")
		removeElementData ( source, "FPS")	
		removeElementData ( source,"IsSpawned" )
		--removeElementData ( source,"Resoultion" )
		removeElementData ( source, "Damage")
			if p_dmg[source] then
				p_dmg[source] = nil
			end
			if help_t[source] then
				destoyCallHelp(source)
			end
			if minimize_t[source] then
				minimize_t[source] = nil
			end
			alpha_p[source] = nil
	end
	addEventHandler ( "onPlayerQuit", getRootElement(), bm_quitPlayer )
	

	function LoadPoczekalniaO()
	setGameType ( "A/D Aspect RELOADED 1.0.6" )
	setMapName ( "Main Lobby" )
	local players = getElementsByType("player")
		for k,v in ipairs(players) do
			ToogleFight(v,false)
		end
	end
	LoadPoczekalniaO()

	addEvent ( "spawn_player_" )
	function spawn_player_(gracz,skin)
		if gracz ~= nil then
			if getElementType(gracz) == "player" then
				local rand_int =  math.random(1,table.getn(wait_spawns_t))
				local rand_rot = math.random(1,360)
				local team_p = getPlayerTeam(gracz)
				setElementParent(gracz,Team_parr[team_p])
				if skin == true then
					removePedFromVehicle ( gracz )
					removeElementData ( gracz, "Health")
					setElementInterior ( gracz,wait_spawns_t.interior,wait_spawns_t[rand_int][1]+math.random(-2.5,2.5),wait_spawns_t[rand_int][2]+math.random(-2.5,2.5),wait_spawns_t[rand_int][3])
					setElementPosition( gracz,wait_spawns_t[rand_int][1]+math.random(-2.5,2.5),wait_spawns_t[rand_int][2]+math.random(-2.5,2.5),wait_spawns_t[rand_int][3])
					setElementFrozen ( gracz,true )
					return false
				end
			--	 setPedAnimation(gracz)
				setElementFrozen ( gracz,false )
				spawnPlayer ( gracz,wait_spawns_t[rand_int][1]+math.random(-2.5,2.5),wait_spawns_t[rand_int][2]+math.random(-2.5,2.5),wait_spawns_t[rand_int][3], rand_rot, Wynik[team_p],wait_spawns_t.interior)
				setCameraTarget ( gracz)
				removeElementData ( gracz, "Health")
				if alpha_p[gracz] and isTimer(alpha_p[gracz]) then
					killTimer ( alpha_p[gracz] ) 
					alpha_p[gracz] = nil
				end
				setElementAlpha(gracz,255)
				if getElementData ( sett,"Round" ) ~= 0 and getElementData ( sett,"Checking" ) == 0 then
					callClient(  gracz, "CreateRoundTimer",RoundLst_s)
					callClient( gracz, "SetPlayerSpectateEnable" )
					callClient( gracz,"createHudManufacture",getTeamByType("Attack"),getTeamByType("Defense"))
					if RoundPaue == true then
						callClient( gracz, "PauseRound" )
						setGameSpeed(0)
					end
				else
					outputChatBox ( "#FF0000** You can spawn vehicle #5599FFby cmd /car [id/name]", gracz, 255, 255, 255, true )
					ToogleFight(gracz,false)
				end
				triggerEvent ( "BaseMode:onPlayerSelectTeam", gracz, Wynik[team_p] )
			end
		end
	end
	addEventHandler ( "spawn_player_", getRootElement(), spawn_player_ )
local buffer_b_type = ""	
	function onMapLoadOrUnload( res )
		if res ~= getThisResource() then
			local name = tostring(getResourceName(res))
				if name == tostring(getElementData(attach_data,"map")) then
					MapRootElement = getResourceRootElement(res)
					local int = get(name..".#interior") or 0
					setElementData(sett,"m_interior",int)
					if LoadedMapInfo[2] == "base" then
						local b_type = get(getResourceName(res)..".#type")
						setElementData(sett,"b_type",b_type)
						 buffer_b_type = b_type
							if type(b_type) ~= "string" then
								outputChatBox ( "#FF0000** Error:#0AC419 This base is not compatibile( Wrong setting #type ), loading cancelled.",getRootElement(), 255, 255, 255, true )
									stopResource(res)
										setElementData(attach_data,"map","main")
										destroyAllMapElements(attach_data)
									LoadedMapInfo = nil LoadedMapInfo = {}
									callClient( getRootElement(), "removeLoadingGui")
								return false
							end	
					end	
					loadround(LoadedMapInfo[1],LoadedMapInfo[2],LoadedMapInfo[3] )
				end
		end		
	end	
	
	
	function loadround(gracz,typen,name )
	local TeamSpawns = {}
	TeamSpawns[1] = getElementsByType ( "Team1",MapRootElement )
	TeamSpawns[2] = getElementsByType ( "Team2",MapRootElement)
	granade_use = {}
		if table.getn(TeamSpawns[1]) < 10 or table.getn(TeamSpawns[2]) < 10 then
			outputChatBox ( "#FF0000** Error:#0AC419 This "..typen.." is not compatible( Not enough spawns, required 10 per team).", gracz, 255, 255, 255, true )
			stopResource(tr)
			setElementData(attach_data,"map","main")
			destroyAllMapElements(attach_data)
			LoadedMapInfo = nil LoadedMapInfo = {}
			callClient( getRootElement(), "removeLoadingGui")
			return
		end
		local marker_o = getElementsByType ( "Central_Marker",MapRootElement ) 
			if getElementData(marker_o[1], "posX") == false then
			stopResource(tr)
			setElementData(attach_data,"map","main")
			outputChatBox ( "#FF0000** Error:#0AC419 Couldn't load central markers data", gracz, 255, 255, 255, true )
			destroyAllMapElements(attach_data)
			LoadedMapInfo = nil LoadedMapInfo = {}
			callClient( getRootElement(), "removeLoadingGui")
			return
			end
		tP = nil tP = {}	
		tP[t1_] = 0 tP[t2_] = 0
		if typen == "base" or typen == "arena" then
			if typen == "base" then
				local marker_t = {}
				marker_t[1] = getElementData(marker_o[1], "posX")
				marker_t[2] = getElementData(marker_o[1], "posY")
				marker_t[3] = getElementData(marker_o[1], "posZ")
				--local mark = createMarker ( marker_t[1], marker_t[2], marker_t[3], "cylinder", 2, 0, 110, 255, 150)
				local mark = createMarker ( marker_t[1], marker_t[2], marker_t[3], "cylinder", 2, 210, 210, 210, 100)
				local f1 = createObject(2914,marker_t[1], marker_t[2]-0.5, marker_t[3],0, 0, 89 )
				local f2 = createObject(2914,marker_t[1], marker_t[2]+0.5, marker_t[3],0, 0, 270 )
				setElementParent (f1, attach_data ) setElementParent (f2, attach_data )
				setElementParent ( mark, attach_data )
				GlobalMarker = mark
				addEventHandler("onMarkerHit", GlobalMarker, onBaseMode_MarkerHit)
				addEventHandler("onMarkerLeave", GlobalMarker, onBaseMode_markerLeave )
				local bl = createBlip (  marker_t[1], marker_t[2], marker_t[3], 19 )
				setElementParent ( bl, attach_data )
				local timerint = tonumber(((roundtimers[1][1]*60)*1000) + (roundtimers[1][2]*1000))
				CreateRoundTimer(timerint)
				callClient(  getRootElement(), "CreateDefRush",marker_t[1], marker_t[2])
				setMapName ( "Base: "..tostring(name) )
				setElementData ( sett,"Round", 1 )
				setElementID ( GlobalMarker,'main-marker' )
					for k,v in ipairs(TeamSpawns[1]) do
						local addf = destroyElement( v )
					end
					--local node = getResourceConfig (  ':' .. getResourceName(getThisResource()) ..'others/map.map' )
					local node = xmlLoadFile  (  'others/map.map' )
				--	outputServerLog(tostring( node ))
						maps_node = loadMapData ( node, MapRootElement )
						xmlUnloadFile ( node )
			else
				local timerint = tonumber(((roundtimers[2][1]*60)*1000) + (roundtimers[2][2]*1000))
				CreateRoundTimer(timerint)
				setElementData ( sett,"Round", 2 )
				setMapName ( "Arena: "..tostring(name) )
			end	
		end_tick_count = getTickCount()	
		setGameType ( "A/D Aspect 1.0.4" )	
		t1_ = getTeamByType("Attack")
		t2_ = getTeamByType("Defense")
		spawn_types = nil spawn_types = {[t1_]="Team1",[t2_] ="Team2"}	
		setElementData(t1_,"Health",0) setElementData(t2_,"Health",0)
		local players = getElementsByType("player")
		for k,v in ipairs(players) do
			ToogleFight(v,true)
--			fadeCamera(v,false)
			removePedFromVehicle ( v )
			removeElementData ( v, "Health")
		end
		for k,v in pairs(veh_in_lobby) do
			destroyElement(v)
			veh_in_lobby[k] = nil
		end		
		takeAllWeapons ( getRootElement())
		setElementData ( sett,"RoundInt", name )
		setElementData ( sett,"RoundName", typen )
		end
	end

	function Start(player,cmdname,nameS,vote)
	lv_arg = {}
		if vote ~= true then
			if IsPlayerAdmin(player) == false then
				outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", player, 255, 255, 255, true )
				return
			end	
		end
		if getTickCount() - start_cmd_fix < 4850 then
			outputChatBox ( "#FF0000** Error:#0AC419 Wait until the end of round ( left "..math.round((4.8-(getTickCount() - start_cmd_fix )/1000),2) .." s ) .", player, 255, 255, 255, true )
			return
		end
		if ( vote == "rand" or vote == "random" or vote == "r" ) and cmdname == "base" then
			nameS =	_core_randombase()
		end	
		if type( nameS ) == "nil" then
			outputChatBox ( "#FF0000** Error:#0AC419 Use /"..cmdname.." [number].", player, 255, 255, 255, true )
			return
		end
		if getElementData ( sett,"Round" ) ~= 0 then
			outputChatBox ( "#FF0000** Error:#0AC419 Round has actually started.", player, 255, 255, 255, true )
			return
		end

		local res_name = cmdname.."_"..nameS
		local root = getResourceFromName ( res_name )
		if root == false then
			outputChatBox ( "#FF0000** Error:#0AC419 Can't load "..cmdname.." #FF0000"..nameS.." #0AC419( file doesn't exist ).", player, 255, 255, 255, true )
			return
		end
		local root_state = getResourceState ( root  )
		if root_state == "failed to load" then
			outputChatBox ( "#FF0000** Error:#0AC419 Can't load "..cmdname.." #FF0000"..nameS.." #0AC419("..getResourceLoadFailureReason ( root )..").", player, 255, 255, 255, true )
			return
		end
		if vote ~= "-nt" then
			if countPlayersInTeam(team1) == 0 or countPlayersInTeam(team2) == 0 then
				outputChatBox ( "#FF0000** Error:#0AC419 Not enough players in teams. Starting "..cmdname.." is stopped.", player, 255, 255, 255, true )	
				return
			end
		end	
		
		setElementData ( sett,"_g_spwn_prot",true)
		exports.votemanager:stopPoll ()
		LoadedMapInfo = {player,cmdname,nameS}
		tr = root
		setElementData(attach_data,"map",res_name)
		if root_state == "running" then
			stopResource(root)
		end
	setTimer(startResource,1000,1,root)
	destroyAllMapElements(attach_data)
		if isTimer ( _core_a_t.timer ) == false then
			_core_a_t.timer = setTimer(_core_acbug ,500,0)
		end
	end
	addCommandHandler( "arena",Start)
	addCommandHandler( "base",Start)
	
	
	

	
	function _core_randombase()
	
	
	--// COS nie tak z ta funckja od sprawdzania granych juz baz!
	
	
	local start_time = getTickCount()
		local category_ = {} -- glowna tablica
		local all_bases = {}
		local to_random = {}
		local to_random_f = {}
		local cat = {["Underground Parking"]={0,6},["Outdoor Parking"]={7,13},["Standard"]={14,23},["Outdoors"]={24,62},["Outdoors with Building"]={63,76}}  -- tablica z kategoriami + zakres numerow
		local cat_l = {["Underground Parking"]=1,["Outdoor Parking"]=1,["Standard"]=3,["Outdoors"]=1,["Outdoors with Building"]=1}  -- tablica z kategoriami + zakres numerow
		local cat_f = {"Underground Parking","Outdoor Parking","Standard","Outdoors","Outdoors with Building"} -- tablica z kategoriami
		
		if #history_data > 1 then
	--	outputChatBox( tostring ( history_data[#history_data-1][2] )..' - '..tostring(  history_data[#history_data][2] ) )
	
		--////////////////////////////////////////////////////////////////////////////////
		--//// W przypadku kategorii standard gdy drugi raz wylosowalo ta baze, dodatkowo sprawdzic czy nie bylo grane
			if history_data[#history_data-1][2] ~=  history_data[#history_data][2] then 
				return  history_data[#history_data][2]
			end
		elseif #history_data > 0 then
			return  history_data[#history_data][2]	
		end

		
		for k,v in pairs(cat)  do
		outputChatBox('Category Count '..tostring( k ).." : "..tostring( _core_random_was( k ) ) )
		--	if findMapInHistory("base", k,getTeamByType("Defense")) == true then
			if _core_random_was( k ) < cat_l[k] then
				for i=v[1],v[2] do
					table.insert( all_bases, i )
				end
				
			end
			
		end
		--- zwiekszyc losowosc dodajac wiecej powtorzen trololo
		local buffers = {base=all_bases,work_s={}}
		for a=1, math.random(30,60 ) do
			
			for i=1, #buffers.base do
				local ran_ = math.random(1,#buffers.base ) 
				table.insert( buffers.work_s, buffers.base[ran_] )
				table.remove( buffers.base,ran_) 
			end
				buffers.base = {}
				buffers.base = buffers.work_s
				buffers.work_s = {}
		end
		
		--[[
		local n_ = #all_bases
		for i=1,n_ do

			local ran_ = math.random(1,#all_bases ) 
			table.insert( to_random, all_bases[ran_] )
			table.remove( all_bases,ran_) 
			
		end		
		
		for i=1,#to_random do

			local ran_ = math.random(1,#to_random ) 
			table.insert( to_random_f, to_random[ran_] )
			table.remove( to_random,ran_) 
			
		end
		for g=1,25 do
		
		
		end]]
		
		
		
	--[[	for k,v in ipairs(buffers.base)  do
		outputChatBox(tostring(k)..' '..tostring(v))
		end]]
		local random_ = math.random(1, #buffers.base)
				--outputChatBox('adsdasdasadsadsds '..tostring(#buffers.base).." "..tostring( random_ ))
		outputChatBox('Czas wykonania '..tostring(getTickCount() - start_time ))
		return  buffers.base[random_]
	end
		
	function lasalsls()
		outputChatBox('wynik: '..tostring( _core_randombase() ))
	end
	addCommandHandler('trololo',lasalsls)
	
	function _core_random_was(category)
		local rt_i = {}
			if #history_data == 0 then
				return 0
			end	
			for k,v in pairs( history_data)  do
				if v[1] == 'base' and v[6] == category then
					table.insert(rt_i,category)
				end
			end
		return #rt_i
	end
	
	

	
	function EndOfRoundCmd(gracz)
		if IsPlayerAdmin(gracz) == false then 
			outputChatBox ( "#FF0000** Error:#0AC419 You are not admin.", gracz, 255, 255, 255, true )
			return
		end	
		local sts = getElementData ( sett,"Round" )
		if sts == 0 then
			outputChatBox ( "#FF0000** Error:#0AC419 Round isn't started.", gracz, 255, 255, 255, true )
			return false
		end
		if getTickCount() - end_tick_count < 10000 then
			outputChatBox ( "#FF0000** Error:#0AC419 Round isn't started.", gracz, 255, 255, 255, true )
			return false
		end
			removeCommandHandler ( "end", EndOfRoundCmd )
			countDmg()
			setTimer(countDmg,1000,1)
			callClient( getRootElement(), "end_of_the_round","Round ended via /end command." )
			setTimer(slowGameSpeed,50,10)
			--FinishRound(getElementData(sett,"Round"),100,true) 
			setTimer(FinishRound,500,1,getElementData(sett,"Round"),100,KillT)
			setTimer(function()  setGameSpeed(1) addCommandHandler ( "end", EndOfRoundCmd ) end,4000,1)
	end
	addCommandHandler ( "end", EndOfRoundCmd )
	
function rsp_cmd(player,slot,w_t)
	local t = getPlayerTeam(player)
	local int = getElementInterior(player)
	local pSkin = getPedSkin(player)
	local Rot = getPedRotation(player)
	local x,y,z = getElementPosition(player)
	local Health = getElementHealth(player)
--	 setPedAnimation( player)
	spawnPlayer ( player, x,y,z, Rot, pSkin, int, 0, t )
	setElementHealth(player,Health)
		for i=1,#w_t do
			giveWeapon(player,w_t[i][1],w_t[i][2])
		end
	setPedWeaponSlot ( player, slot )
	setElementAlpha(player,255)
end




function FinishRound(typ,czas,killT)
	if getElementData ( sett,"Checking" ) == 0 then
		setElementData ( sett,"Checking",1 )
		if RoundPaue == true then
			cmd_play_sts = true
			RoundPaue = false
			local Roznica_e = getTickCount()
			getTickEnd_c = getTickEnd_c+(Roznica_e - Roznica_s)
			cmd_play_sts = false
		end
		callClient(getRootElement(),'_core_protect_s',false,'','' ) 
		LoadPoczekalniaO()	
		executeSQLDropTable ("restore_" )
		executeSQLDropTable ("_s_stats_" )
		executeSQLCreateTable ( "restore_", "name TEXT, time TEXT, reason TEXT, hp NUMERIC, weapons TEXT, pos TEXT, veh TEXT, team TEXT" )
		executeSQLCreateTable ( "_s_stats_", "serial TEXT, score TEXT, kills TEXT, deaths NUMERIC, damage TEXT" )

		setTimer(function()
			start_cmd_fix = getTickCount()
			setElementData(attach_data,"map","main")
			stopResource(tr)
			setElementData ( team1,"Active_Players",0  )	 
			setElementData ( team2,"Active_Players",0 )
			setElementData ( team1, "Health",0 )
			setElementData ( team2, "Health",0 )
			removeElementData ( team1, "Health")
			removeElementData ( team2, "Health")
			setElementData ( sett,"Round",0 )
			triggerEvent ( "Aspect:OnRoundEnds",getRootElement() )
			setElementData ( sett,"RoundInt", 0 )
			setElementData ( sett,"RoundName", "Main Lobby" )
			--
			for k,v in pairs(Drop_weapons) do
				DestroyDropElement(k)
			end	
			Drop_weapons = {}
			granade_use = {}
			--destroyAllMapElements(attach_data)
			setElementData ( sett,"Checking",0 )
			local players = getElementsByType("player") 
				for k,v in ipairs(players) do
					setElementData ( v,"IsSpawned", 0 )
					--triggerEvent ( "spawn_player_", v, v )
					removeElementData ( v, "Health")
					if help_t[v] then
						destroyElement(help_t[v]["blip"])
						destroyElement(help_t[v]["arrow"])
					end
				end
				help_t={}
			local blips = getElementsByType("blip") 
				for a,b in ipairs(blips) do
					destroyElement(b)
				end
			P_Blips = nil
			P_Blips = {}
			if isElement (maps_node ) then destroyElement(maps_node ) end
			destroyElement(MapRootElement )
			
			
				setTimer(function()
				--[[local players = getElementsByType("player") 
				for k,v in ipairs(players) do
					triggerEvent ( "spawn_player_", v, v )
				end]]
					if czas ~= 100 then
						ChangeTeamAllPpl()
					else
					--[[	local players = getElementsByType("player") 
						for k,v in ipairs(players) do
							if getPlayerTeam(v) ~= false then
								triggerEvent ( "spawn_player_", v, v )
							end
						end]]
					end
				end,250,1)

				
		end,czas,1)	
		--
		if typ == 1 then 
			if BaseOc == true then  
				removeEventHandler("onMarkerHit", GlobalMarker, onBaseMode_MarkerHit)
				removeEventHandler("onMarkerLeave", GlobalMarker, onBaseMode_markerLeave )
				killTimer(BaseOc_t)
				setElementData ( sett,"Capturing",-1 )
				BaseOc = false
			end	
			Gracze_Partacze = nil
		elseif typ == 2 then 
		end
			if killT == true then
				killTimer(_r_timer )
			end
	end
	collectgarbage ("collect")
end

function IsThisMomentToCheckWhoWon(Attack,Defense,r_type,thisWins,KillT,reason)
	local tA_c = getElementData(Attack,"Active_Players")
	local tD_c = getElementData(Defense,"Active_Players")
	if tA_c == 0 or tD_c == 0 then
		CheckOutWhoWon(Attack,Defense,r_type,thisWins,KillT,reason)
	end
end

function CheckOutWhoWon(Attack,Defense,r_type,thisWins,KillT,reason)
	if thisWins ~= false then
		OneTeamWin(thisWins,KillT,reason)
	else	
		local type1 = getElementData(Attack,"t_type")
		local type2 = getElementData(Defense,"t_type")
		local teamA_Hp = tonumber(CorrectValue(getElementData(Attack,"Health")))
		local teamD_Hp = tonumber(CorrectValue(getElementData(Defense,"Health")))
		local tA_c = getElementData(Attack,"Active_Players")
		local tD_c = getElementData(Defense,"Active_Players")
		--
		if tA_c > tD_c then 
			OneTeamWin(Attack,KillT,reason or "Time is up, the team with more players has won.")
		elseif tD_c > tA_c then 
			OneTeamWin(Defense,KillT,reason or "Time is up, the team with more players has won.")
		else
			if teamA_Hp > teamD_Hp then
			OneTeamWin(Attack,KillT,reason or "Time is up, players count in both teams are the same, team with more health wins.")
			elseif teamD_Hp > teamA_Hp then
			OneTeamWin(Defense,KillT,reason or "Time is up, players count in both teams are the same, team with more health wins.")
			else
				if RoundPaue == false then
					setTimer(countDmg,1000,1)
					--setTimer(FinishRound,3900,1,getElementData(sett,"Round"),100,KillT)
					--setTimer(FinishRound,500,1,getElementData(sett,"Round"),100,KillT)
					FinishRound(getElementData(sett,"Round"),100,KillT)
					callClient( getRootElement(), "end_of_the_round","Time\'s up" )
					setTimer(slowGameSpeed,50,11)
					setTimer(setGameSpeed,4000,1,1)
				end
			end
		end
	end	
end

function returnRoundData()
local t_rtn = {}
	for k,v in ipairs(history_data) do
		for k,v in ipairs(v) do
		end	
		table.insert(t_rtn,{v[1]..": "..v[2],v[10],v[9],(v[6] or ' - '),v[7],v[8]})
	end
	return t_rtn 
end
--local b_fix = true
function OneTeamWin(team,KillT,reason)
	if  RoundPaue == true then	
		return false
	end
	
	
	--if RoundPaue == false and round_mode[1] ~= 'normal' then	
	--b_fix = false
	setTimer(countDmg,1000,1)
--	L()
	--setTimer(function() callClient( getRootElement(), "LoadingAnimation",1000,"CreateResultsTable", team,getMapName (),reason) setGameSpeed(1) end,3500,1)
	
	setElementData ( team,"Score",(getElementData (team,"Score")+1))	 
	--//			typ mapy			id						attack					obrona		zwyciesca 		typ bazy
	local m_win = false
	local _r_c = 7
	--[[if #history_data == _r_c then
		local copy = history_data
			history_data = {}
				for i=2,_r_c do
				table.insert(history_data,i-1,copy[i])
				end
			table.insert(history_data,{LoadedMapInfo[2],LoadedMapInfo[3],getTeamName(getTeamByType("Attack")),getTeamName(getTeamByType("Defense")),getTeamName( team),buffer_b_type,getElementData (team,"Score"),getElementData (team,"Health"),getTeamByType("Defense"),team} )		
	else]]
	--	history_data[#history_data+1] = {LoadedMapInfo[2],LoadedMapInfo[3],getTeamName(getTeamByType("Attack")),getTeamName(getTeamByType("Defense")),getTeamName( team)}
	table.insert(history_data,{LoadedMapInfo[2],LoadedMapInfo[3],getTeamName(getTeamByType("Attack")),getTeamName(getTeamByType("Defense")),getTeamName( team),buffer_b_type,getElementData (team,"Score"),getElementData (team,"Health"),getTeamByType("Defense"),team} )	
	--end
--	outputChatBox('DEBUG: '..tostring(team).. ' '..tostring(KillT )..' '..tostring( reason ))
	local rrrr = returnRoundData()
--	outputChatBox('DEBUG: '..tostring(team).. ' '..tostring(KillT )..' '..tostring( reason )..' '..tostring( rrrr ))
--	outputChatBox('DEBUG: '..tostring(team).. ' '..tostring(KillT )..' '..tostring( reason )..' '..tostring( rrrr )..' '..tostring( #rrrr ))
	callClient( getRootElement(), "CreateResultsTable_", team,getMapName (),tostring(reason),returnRoundData(),m_win) setGameSpeed(1)
	setTimer(slowGameSpeed,50,10)
	setTimer(setGameSpeed,3000,1,1)
	FinishRound(getElementData(sett,"Round"),5000,KillT)
--	history_data = {LoadedMapInfo[2],LoadedMapInfo[3]},getTeamByType("Attack"),getTeamByType("Defense"), team )
--	setTimer(function( ) b_fix = true end,2000,1)
--	end
end

function slowGameSpeed()
	setGameSpeed(getGameSpeed()-0.1)
end

function findMapInHistory(type_,category,team) --// base, arena
	local rt_i = {}
	if #history_data == 0 then
		return true
	end	
	for k,v in pairs( history_data)  do
		if v[9] == team and v[1] == type_ and v[6] == category then
			table.insert(rt_i,category)
		end
	end
	if #rt_i > 0 then
		if category == "Standard" and #rt_i < 2 then
			return true
		end
		return false
	else
		return true
	end	
end

addEvent ( "SpawnPlayerOnRound" ,true)
	function SpawnPlayerOnRound(v,intspawn,ch,pc,ch2)
	local pT = getPlayerTeam(v)
	local ac = getElementData ( pT,"Active_Players")	 
			setElementData ( pT,"Active_Players",(ac+1)  )	 
				setElementData ( v,"IsSpawned", 1 )
				tP[pT] = tP[pT]+1
					if intspawn ~= nil then tP[pT] = intspawn end
				local spawn_t = getElementsByType ( spawn_types[pT],MapRootElement)
				local spawn_int = tP[pT]
				local spawns_t
					if spawn_int > 10 then
					spawn_int,r_s = ReturnGandR_s(spawn_int)
					spawns_t = {ObliczSpawn( getElementData(spawn_t[spawn_int], "posX"),getElementData(spawn_t[spawn_int], "posY"),getElementData(spawn_t[spawn_int], "posZ"),0.6,r_s )}
					spawns_t[4]=r_s
					else
					spawns_t = {getElementData(spawn_t[spawn_int], "posX"),getElementData(spawn_t[spawn_int], "posY"),getElementData(spawn_t[spawn_int], "posZ"),0}
					end
					setElementData ( v, "Health",100 )
					--spawnPlayer ( v, spawns_t[1], spawns_t[2],spawns_t[3], spawns_t[4], Wynik[pT],getElementData(sett,"m_interior")  )
		--			 setPedAnimation( v)	
					spawnPlayer ( v, spawns_t[1], spawns_t[2],spawns_t[3], spawns_t[4], Wynik[pT], getElementData(sett,"m_interior") )
					setCameraTarget ( v )
				local r,g,b = getTeamColor(pT)
			setElementParent(v,Team_parr[pT])
		P_Blips[v] = createBlipAttachedTo ( v, 0, 1.75, r,g,b,150,0,3000,Team_parr[pT] )
		callClient( v, "AddSpawnProtect",1 )
		if ch ~= nil then
		callClient( v, "AddSpawnProtect",50 )	
		end
		setElementAlpha(v,255)
	--	UpdateTeamVar("Health",pT,"%.0f",0)
	--	UpdateHealth(pT,getElementHealth(v))
		
	end
addEventHandler ( "SpawnPlayerOnRound", getRootElement(), SpawnPlayerOnRound )	

 
function add_cmd(gracz,cmd,arg)
	if IsPlayerAdmin(gracz) == false then 
		outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", gracz, 255, 255, 255, true )
		return
	end	
	if getElementData ( sett,"Round" ) == 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 Round hasn't actually started.", gracz, 255, 255, 255, true )
        return
	end
	local graczfi = getPlayerByID(tonumber(arg))
	if not graczfi then
		outputChatBox ( "#FF0000** Error:#0AC419 Bad player ID.", gracz, 255, 255, 255, true )
		return
	end
	if getElementData ( graczfi,"IsSpawned" ) == 1 then
		outputChatBox ( "#FF0000** Error:#0AC419 This player is actually on round.", gracz, 255, 255, 255, true )
		return
	end
	local pT = getPlayerTeam(graczfi)
	if pT == false then
		outputChatBox ( "#FF0000** Error:#0AC419 This player didn't choose team.", gracz, 255, 255, 255, true )
		return
	end
	callClient( graczfi, "_core_crouchBug")
	callClient( graczfi, "RemoveSpectateMode",true )
	granade_use[graczfi] = nil
	local rootO =  getRootElement()
	callClient( graczfi, "replaceOnClientStart",LoadedMapInfo[2].."_"..LoadedMapInfo[3]  )
	setTimer(function()
	local poss 
		if tP[pT] == 0  then
			poss = 1
		else
			poss = math.random(1,	tP[pT] )		
		end
	SpawnPlayerOnRound(graczfi,poss,true)
	if alpha_p[graczfi] and isTimer(alpha_p[graczfi]) then
		killTimer ( alpha_p[graczfi] ) 
		alpha_p[graczfi] = nil
	end
	setElementAlpha(gracz,255)
	outputChatBox ( "#FF0000** Info:#0AC419 Admin added player: #FF0000"..tostring(getPlayerName(graczfi)).."#0AC419 to round.", rootO, 255, 255, 255, true )
	end,500,1)
end
addCommandHandler( "add",add_cmd)

function resetscore_cmd(gracz,cmd,arg)
	if getElementData ( sett,"Round" ) == 0 then
		if IsPlayerAdmin(gracz) == false then 
			outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", gracz, 255, 255, 255, true )
			return
		end	
		if getElementData ( sett,"Round" ) ~= 0 then
			outputChatBox ( "#FF0000** Error:#0AC419 Round has actually started.", gracz, 255, 255, 255, true )
			return
		end
		setElementData(team1,"Score",0)	
		setElementData(team2,"Score",0)	
			local players = getElementsByType("player")
				for k,v in ipairs(players) do
					setElementData(v,"Kills",0)
						setElementData(v,"Deaths",0)
					setElementData(v,"Damage",0)	
					setElementData(v,"Score",0)	
				end	
		outputChatBox ( "#FF0000** Info:#0AC419 Admin: #FF0000"..tostring(getPlayerName(gracz)).."#0AC419 reset all teams and players score.", getRootElement(), 255, 255, 255, true )
	end
end
addCommandHandler( "resetscore",resetscore_cmd)
addCommandHandler( "reset",resetscore_cmd)


function gunmenu_cmd(gracz,cmd,arg)
	if IsPlayerAdmin(gracz) == false then 
		outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", gracz, 255, 255, 255, true )
		return
	end	
	if getElementData ( sett,"Round" ) == 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 Round hasn't actually started.", gracz, 255, 255, 255, true )
        return
	end
	local graczfi = getPlayerByID(tonumber(arg))
	if not graczfi then
		outputChatBox ( "#FF0000** Error:#0AC419 Bad player ID.", gracz, 255, 255, 255, true )
		return
	end
	if getElementData ( graczfi,"IsSpawned" ) == 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 This player is not actually on round.", gracz, 255, 255, 255, true )
		return
	end
	local pT = getPlayerTeam(graczfi)
	if pT == false then
		outputChatBox ( "#FF0000** Error:#0AC419 This player didn't choose team.", gracz, 255, 255, 255, true )
		return
	end
	
	local rootO =  getRootElement()
	callClient( graczfi, "gunmenu" )
	outputChatBox ( "#FF0000** Info:#0AC419 Admin gives player: #FF0000"..tostring(getPlayerName(graczfi)).."#0AC419 the weapon menu.", rootO, 255, 255, 255, true )
end
addCommandHandler( "gunmenu",gunmenu_cmd)

function remove_cmd(gracz,cmd,arg)
	if IsPlayerAdmin(gracz) == false then 
		outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", gracz, 255, 255, 255, true )
		return
	end	
	if getElementData ( sett,"Round" ) == 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 Round hasn't actually started.", gracz, 255, 255, 255, true )
        return
	end
	local graczfi = getPlayerByID(tonumber(arg))
	if not graczfi then
		outputChatBox ( "#FF0000** Error:#0AC419 Bad player ID.", gracz, 255, 255, 255, true )
		return
	end
	if getElementData ( graczfi,"IsSpawned" ) == 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 This player is not in round.", gracz, 255, 255, 255, true )
		return
	end
	local pT = getPlayerTeam(graczfi)
	if pT == false then
		outputChatBox ( "#FF0000** Error:#0AC419 This player didn't choose team.", gracz, 255, 255, 255, true )
		return
	end
	local rootO =  getRootElement()
	setElementData ( graczfi,"IsSpawned",0)
	--
	outputChatBox ( "#FF0000** Info:#0AC419 Admin has removed player: #FF0000"..tostring(getPlayerName(graczfi)).."#0AC419 from round.", rootO, 255, 255, 255, true )
	--setElementData ( graczfi, "Health","Dead" )
	granade_use[graczfi] = nil
	UpdateHealth(pT,math.round(getElementHealth(graczfi), 0)*-1)
	destroyElement(P_Blips[graczfi])
		if getElementData ( sett,"Checking" ) == 0 then	
			local sTeam = getPlayerTeam(graczfi) 
			local sTa = getElementData ( sTeam,"Active_Players" )
			setElementData (sTeam ,"Active_Players", sTa-1)
			IsThisMomentToCheckWhoWon(getTeamByType("Attack"),getTeamByType("Defense"), getElementData ( sett,"Round" ),false,true)
		end
	callClient(graczfi,'_core_protect_s',false,'','' ) 	
	setTimer(function()
	callClient( graczfi, "SetPlayerSpectateEnable" )
	spawn_player_( graczfi, true)
	end,math.max(50,getPlayerPing(graczfi)) +500,1)
		
end
addCommandHandler( "remove",remove_cmd)

local l_log = {}
function _core_onScreenShot( theResource, status, imageData,timestamp, tag )

if getThisResource() == theResource and status == 'ok' then
		local file = fileCreate ( "PlayerScreens/"..tag..".jpeg" )
		fileWrite (file,imageData)
		fileClose ( file )
		local g_s = md5(tag)
		outputChatBox('#FF0000[ SCREEN ] Screen: #FFD700' .. string.sub(tag,1,34) .. '...#FF0000 has been saved successfully.', l_log[g_s] , 255, 0, 0,true)
		--callClient(  l_log[g_s], "_core_sreen_show",imageData,taq)
		l_log[g_s] = nil
	end
end
addEventHandler( "onPlayerScreenShot", root,_core_onScreenShot)

function screen_cmd(gracz,cmd,arg,q,taq,w,h)
	if IsPlayerAdmin(gracz) == false then 
		outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", gracz, 255, 255, 255, true )
		return
	end	
	if arg == nil or q == nil or taq == nil then
	outputChatBox ( "#FF0000** Error:#0AC419 usage of this command: /screen id quaility(0-100) [taq] [width] [height]", gracz, 255, 255, 255, true )
		return
	end
	
	local graczfi = getPlayerByID(tonumber(arg))
	if not graczfi then
		outputChatBox ( "#FF0000** Error:#0AC419 Bad player ID.", gracz, 255, 255, 255, true )
		return
	end
		if w ~= nil and h ~= nil then
			_screen_c(graczfi,w,h,q,taq,gracz)
		else
			callClient(  graczfi, "_core_sreen",q,taq,gracz)
		end
	end
	addCommandHandler('screen',screen_cmd)
	
	function _screen_c(graczfi,w,h,q,taq,gracz)
	local timed = getRealTime( )
	local tagg = ''..getPlayerName( graczfi )..'_'..timed.monthday..'-'..(timed.month+1)..'_'..(timed.hour)..'-'..' '..(timed.minute)..'-'..timed.second..'_'..math.random(0.0,9999.9)..'_'.. (taq or '')..'_IP_'..getPlayerIP(graczfi)..'_SERIAL_'..getPlayerSerial(graczfi)
	l_log[md5(tagg)] = gracz
	takePlayerScreenShot( graczfi, w ,h , tagg, math.min(75,math.max(20, q)) , 5000)
	--takePlayerScreenShot( graczfi, w ,h , tagg,q , 20000)
	end
	


--//////////////////////////////////////////////////////////////////////



function _panel_save(gracz,name,data)
local file = xmlCreateFile  ( ":"..getResourceName(getThisResource()).."/cfg/"..name..".xml","settings" )
local node = xmlCreateChild ( file , '_cfg' )
	xmlNodeSetAttribute ( node,'_data',toJSON(data) )
		xmlSaveFile ( file )
		xmlUnloadFile ( file )
		_panel_load(gracz,name)		
	local confings = fromJSON (get(""..getResourceName(getThisResource()).."._@cfgs"))
		for k,v in pairs( confings ) do
			if v == name then
				return false 
			end	
		end
		table.insert(confings,name)
		set(""..getResourceName(getThisResource()).."._@cfgs", toJSON( confings ))
end

function _panel_delete(gracz,name)


local file = fileDelete ( ":"..getResourceName(getThisResource()).."/cfg/"..name..".xml","settings" )
--outputChatBox ( tostring( file ))

		
	local confings = fromJSON (get(""..getResourceName(getThisResource()).."._@cfgs"))
	--outputChatBox ( tostring( #confings ))
		for k,v in pairs( confings ) do
			if v == name then
				table.remove(confings,k)
			end	
		end
		set(""..getResourceName(getThisResource()).."._@cfgs", toJSON( confings ))
		_panel_load(gracz,confings[#confings])		
	
end
	
function _panel_load(gracz,name,arena)
cfg_file = name

	if name then
	
		set(""..getResourceName(getThisResource()).."._@cfg", name)
	end
local confing = name or get(""..getResourceName(getThisResource()).."._@cfg")
local confings = fromJSON (get(""..getResourceName(getThisResource()).."._@cfgs"))
local file = xmlLoadFile ( ":"..getResourceName(getThisResource()).."/cfg/"..confing..".xml") 
	if file == false then
		set(""..getResourceName(getThisResource()).."._@cfg",'default')
		_panel_load(gracz,get(""..getResourceName(getThisResource()).."._@cfg"),arena)
	end	

local node = xmlFindChild ( file, '_cfg', 0 )
local table_ =  fromJSON ( xmlNodeGetAttribute ( node, '_data' ) ) 
loadGameSettings(table_,arena)
	if gracz then
	callClient( gracz, "_panel_load",table_,confings,confing)
	end

end

		
	function itWas(ta,ar)
		for k1, v1 in ipairs ( ta ) do
			if v1[1] == ar then
				return false
			end
		end
		return true
	end

	function ifNotWas(ta,ar)
		for k1, v1 in ipairs ( ta ) do
			if v1 == ar then
				return false
			end
		end
		return true
	end
	
	--[[function findDuplicate(t)
	local t_n = {}
		for k, v in ipairs ( t ) do
			if itWas(t_n,v) == true then
			table.insert(t_n,v)
			end
		end
	return t_n
	end
	]]
	
	function CheckMaps(t)
		local n_t = {}
		for k, v in ipairs ( t ) do
			if getResourceFromName ( v[2].."_"..v[1] ) then
				table.insert(n_t,v)
			end
		end
		return n_t
	end
	
		function findDuplicate(t)
	local t_n = {}
		for k, v in ipairs ( t ) do
			if itWas(t_n,v[1]) == true then
			table.insert(t_n,v)
			end
		end
	return t_n
	end
lv_arg = {}
local vote_tick = getTickCount()
local vote_en = getTickCount()- 50000

function CreateVote(gracz,cmd,type_c,...)
	if getElementData ( sett,"Round" ) ~= 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 Round has actually started.", gracz, 255, 255, 255, true )
        return false
	end
	if vote_maps_s == false then
		outputChatBox ( "#FF0000** Error:#0AC419 Voting is disabled.", gracz, 255, 255, 255, true )
        return false
	end

	-- callClient( gracz, "view_window","vote","Vote maps:")

	if type_c == "base" or type_c == "arena" then
	local n_int = 1
	local timeout_v = _get_("timeout")
		if #lv_arg ~= 0 then
		timeout_v= timeout_v -math.round((getTickCount()-vote_tick)/1000,0)
			if timeout_v == 0 then
				return false
			elseif timeout_v < 0 then
				lv_arg = {}
			end
		else
			 vote_tick = getTickCount()
		end
		for k, v in ipairs ( arg ) do
			arg[k] = {v,type_c}
		end
	local n_vote = {title="Start "..type_c..":",percentage=_get_("percentage"),timeout=timeout_v,allowchange=_get_("allowchange"),maxnominations=_get_("maxnominations"),visibleTo=getRootElement()}
	for k, v in ipairs ( lv_arg ) do
	table.insert(arg,k,v)
	end

	lv_arg = arg
	local v_arg = CheckMaps(findDuplicate(arg ))
	if #v_arg > 1 then
		for k,v in ipairs(v_arg) do
		--	if type(tonumber(v[1])) == "number" then
					if n_int < 9 then
					n_vote[n_int ]={v[2].." "..v[1],"asd800",getRootElement(),v[2],v[1]}
					n_int = n_int +1
					end
		--	end
		end
	n_vote[n_int+1]={"None"}

	else
		--if type(tonumber(v_arg[1][1])) == "number" then
		n_vote.title="Start "..v_arg[1][2].." "..v_arg[1][1]..":"
		n_vote[1]={"Yes","asd800",getRootElement(),v_arg[1][2],v_arg[1][1]}
		n_vote[2]={"No"}
		--end
	end	
	vote_en = false
	exports.votemanager:stopPoll ( )
	vote_by = getPlayerName(gracz)
	exports.votemanager:startPoll (n_vote)
	
	else
		--outputChatBox ( "#FF0000** Error:#0AC419 Bad Vote type.", gracz, 255, 255, 255, true )
		callClient( gracz, "view_window","vote","Vote maps:")
        return
	end
end

function create_vote(gracz,cmd)
	if getElementData ( sett,"Round" ) ~= 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 Round has actually started.", gracz, 255, 255, 255, true )
        return
	end
	if vote_maps_s == false then
		outputChatBox ( "#FF0000** Error:#0AC419 Voting is disabled.", gracz, 255, 255, 255, true )
        return
	end
	if getTickCount() - vote_en < _get_("timeout")*1000 then
		outputChatBox ( "#FF0000** Error:#0AC419 Please wait to current vote end.", gracz, 255, 255, 255, true )
        return false
	end
	callClient( gracz, "view_window","vote","Vote maps:")
end

function create_svote(gracz,maps)
	local timeout_v = _get_("timeout")
	if getTickCount() - vote_en  < timeout_v*1000 then
		outputChatBox ( "#FF0000** Error:#0AC419 Please wait to current vote end.", gracz, 255, 255, 255, true )
        return false
	end

	local n_int = 1
	
	local n_vote = {title="Start Map:",percentage=_get_("percentage"),timeout=timeout_v,allowchange=_get_("allowchange"),maxnominations=_get_("maxnominations"),visibleTo=getRootElement()}
	if #maps > 1 then
		for k,v in ipairs(maps) do
				--	if n_int < 9 then
					n_vote[n_int ]={v[1].." "..v[2],"asd800",getRootElement(),v[1],v[2]}
					n_int = n_int +1
				--	end
		end
	n_vote[n_int+1]={"None"}
	else
		n_vote.title="Start "..maps[1][1].." "..maps[1][2]..":"
		n_vote[1]={"Yes","asd800",getRootElement(),maps[1][1],maps[1][2]}
		n_vote[2]={"No"}
	end	
	exports.votemanager:stopPoll ( )
	vote_by = getPlayerName(gracz)
	exports.votemanager:startPoll (n_vote)
	vote_en =  getTickCount()
end


addEvent("onPollStart")
function DrawVoteCreator()
outputChatBox ( "#FF0000** Voting started by:#FFD700 "..vote_by..".", getRootElement(), 255, 255, 255, true )
vote_en =  getTickCount()
end
addEventHandler("onPollStart",getRootElement(),DrawVoteCreator)

addCommandHandler( "vote",CreateVote)
addEvent("asd800")
function asd800(type_,arg)
Start(getRootElement(),type_,arg,true)

end
addEventHandler("asd800",getRootElement(),asd800)

function vote_carp()
lv_arg = {}
end
--addEventHandler("onPollStop",getRootElement(),vote_carp)
addEventHandler("onPollEnd" ,getRootElement(),vote_carp)

--- Przejmowanie Bazy
Gracze_Partacze = nil
function onBaseMode_MarkerHit ( hitPlayer )
if BaseOc == false then
	if getElementData ( sett,"Round" ) == 1 and getElementData ( sett,"Checking" ) == 0 and isPedInVehicle ( hitPlayer ) == false and getPlayerTeam( hitPlayer) == getTeamByType("Attack") then
	BaseOc = true
	Gracze_Partacze = hitPlayer
	setElementData ( sett,"Capturing",0 )
	BaseOc_t = setTimer(
						function() 
							if RoundPaue == false then
								if isElement ( Gracze_Partacze ) and isPedDead ( Gracze_Partacze ) == false then 
									if getElementData ( sett,"Capturing" )==100 then   
										CheckOutWhoWon(getTeamByType("Attack"),getTeamByType("Defense"), getElementData ( sett,"Round" ),getTeamByType("Attack"),true,"Base has been captured by "..tostring(getPlayerName(Gracze_Partacze)))
										BaseOc = false  
										callClient( Gracze_Partacze, "got_points",30,'Base Capture','')
										triggerEvent("BaseMode:onBaseCaptured",hitPlayer)
									else 
										setElementData ( sett,"Capturing",getElementData ( sett,"Capturing" )+5) 
									end 
								else
									local gi = getPlayerFromAttackInMarker()
									if gi ~= false then
										Gracze_Partacze = gi
									else
										killTimer(BaseOc_t)
										setElementData ( sett,"Capturing",-1 )
										BaseOc = false
										Gracze_Partacze = nil
									end 
								end
							end
						end,1000,21)
	end
end	
end
function getPlayerFromAttackInMarker()
	local players = getPlayersInTeam ( getTeamByType("Attack") )
		for k, v in ipairs ( players ) do
			if isPedDead ( v ) == false and isElementWithinMarker ( v, GlobalMarker ) then 
			return v
			end
		end
		return false
end

function onBaseMode_markerLeave ( leavePlayer)
if BaseOc == true then  
	if getElementData ( sett,"Round" ) == 1 and getElementData ( sett,"Checking" ) == 0 and getPlayerTeam( leavePlayer) == getTeamByType("Attack") then
	if Gracze_Partacze == leavePlayer then
		local gi = getPlayerFromAttackInMarker()
		if gi ~= false then
		Gracze_Partacze = gi
		else
		killTimer(BaseOc_t)
		setElementData ( sett,"Capturing",-1 )
		BaseOc = false
		Gracze_Partacze = nil
		end
	end
	end

end
end

local wepons_models = {
[22]=346,
[23]=347,
[24]=348,
[25]=349,
[29]=353,
[30]=355,
[31]=356,
[33]=357,
[34]=358,
}
function ShitchDropWeaponPoint(colid,id,clip,ammo,player)
local k = FindColinTable(colid)

		
	if id == 0 then
	giveWeapon ( player , Drop_weapons[k][3] , 1, true)
	setWeaponAmmo ( player, Drop_weapons[k][3], Drop_weapons[k][5], Drop_weapons[k][4] )
	 callClient( getRootElement(), "synchronize_drop",colid,id,"del")
	if isElement( Drop_weapons[k][1]) then  destroyElement( Drop_weapons[k][1]) end
	if isElement( Drop_weapons[k][2]) then  destroyElement( Drop_weapons[k][2]) end
	Drop_weapons[k] = {}
	return false
	end
takeWeapon ( player, id )
giveWeapon ( player , Drop_weapons[k][3] , 1, true)
setWeaponAmmo ( player, Drop_weapons[k][3], Drop_weapons[k][5], Drop_weapons[k][4] )
setElementModel(Drop_weapons[k][1], wepons_models[id])
local o = Drop_weapons[k][1]
Drop_weapons[k] = {}
Drop_weapons[k] = {o,colid,id,clip,ammo}
 callClient( getRootElement(), "synchronize_drop",colid,id,"upd")

end

function CreateDropWeaponPoint(x,y,z,id,clip,ammo)
if id ~= false and id ~= nil and wepons_models[id] ~= nil then
local o = createObject ( wepons_models[id] ,x,y,z+0.045,90,0,0  )
setElementInterior(o,getElementData(sett,"m_interior"))
local c = createColSphere (x,y,z+0.75, 1.5 )
setElementID(c,"w_col")
 table.insert(Drop_weapons,{o,c,id,clip,ammo})
 callClient( getRootElement(), "synchronize_drop",c,id,"new",o)
end
end
function testcmd(p,cmd,id,clip,ammo)
local x,y,z = getElementPosition(p)
CreateDropWeaponPoint(x,y,z,tonumber(id),tonumber(clip),tonumber(ammo))
end
--addCommandHandler("add_w", testcmd)
function FindColinTable(id)
	for k,v in pairs(Drop_weapons) do
		if v[2] == id then
		return k
		end
	end
	return false
end


function DestroyDropElement(k)
	callClient( getRootElement(), "synchronize_drop",Drop_weapons[k][2],Drop_weapons[k][3],"del")
	if isElement(Drop_weapons[k][1]) then destroyElement( Drop_weapons[k][1]) end
	if isElement(Drop_weapons[k][2]) then destroyElement( Drop_weapons[k][2]) end
	Drop_weapons[k] = {}
end
--//spawn auta w poczekalni

	
function spawnCarLobby(player,cmd,id)
local disabled = {432,592,553,476,447,520,425,577,430}
	if getElementData ( player,"IsSpawned" ) == 0 and getElementData (sett,"Round" ) == 0 then
	if _get_("vehicles_in_lobby") == false then
		outputChatBox ( "#FF0000** #0AC419Server administrator #0e8b9ddisallows vehiles in #0AC419main lobby :X.", player, 255, 255, 255, true )
		return false
	end
	id = getVehicleModelFromName ( id ) or tonumber(math.round(id,0))
			if veh_in_lobby[player] and getElementModel(veh_in_lobby[player]) == id and getPedOccupiedVehicle ( player ) == veh_in_lobby[player]  then
				fixVehicle ( veh_in_lobby[player] )
				local rX,rY,rZ = getVehicleRotation (veh_in_lobby[player] )
				setVehicleRotation (veh_in_lobby[player],0,0,rZ )
				warpPedIntoVehicle (player,(veh_in_lobby[player] ))
				return false	
			end	
		if id ~= false then
			local vtype = getVehicleType ( id )	
			if checkT(disabled,id)  == true or vtype == "Train" or vtype == "Trailer" then
				outputChatBox ( "#FF0000** #0AC419This vehicle is not allowed.", player, 255, 255, 255, true )
				return false
			elseif  vtype == "Boat" and isElementInWater ( player ) == false then
				outputChatBox ( "#FF0000** #0AC419To use boat go to water :D.", player, 255, 255, 255, true )
				return false
			end
			local rot = getPedRotation(player)
				if veh_in_lobby[player] and isElement(veh_in_lobby[player]) then
					if getPedOccupiedVehicle ( player ) == veh_in_lobby[player]  then 
						local a,b,c = getVehicleRotation (veh_in_lobby[player] )
						rot = c
					end
					destroyElement(veh_in_lobby[player])
					veh_in_lobby[player] = nil
				end
			local x,y,z = getElementPosition(player)
			local vX,vY,vZ = getElementVelocity( player )
			local car = createVehicle ( id, x,y,z+0.25,0,0,rot )
			setElementInterior( car, getElementInterior ( player ) )
			local rand_c = {[1]={math.random(0,255),math.random(0,255),math.random(0,255)},[2]={math.random(0,255),math.random(0,255),math.random(0,255)}}
				if car == false then
					outputChatBox ( "#FF0000** #0AC419Bad vehicle id/name.", player, 255, 255, 255, true )
					return
				end
				veh_in_lobby[player] = car
				setVehicleColor ( car ,rand_c[1][1],rand_c[1][2],rand_c[1][3],rand_c[2][1],rand_c[2][2],rand_c[2][3],rand_c[1][1],rand_c[1][2],rand_c[1][3],rand_c[2][1],rand_c[2][2],rand_c[2][3] )
				warpPedIntoVehicle (player,car )
				setElementVelocity(car,vX,vY,vZ)
			outputChatBox ( "#FF0000** #0AC419Vehicle created successfully.", player, 255, 255, 255, true )
			end
		end	
	end	
addCommandHandler("car", spawnCarLobby)

function checkT(t,e)
	for i=1,#t do
		if t[i] == e then
			return true
		end
	end
end

function getPanelConfigs(n)
local gowno = getTickCount()
local aja = xmlLoadFile (":"..getResourceName(getThisResource()).."/cfg/cfgs.xml" )
local node = xmlFindChild ( aja, "cfgs", 0 )
local att =  xmlNodeGetAttributes ( node )

local cfgs_t = {}
	for name,value in pairs ( att ) do
	table.insert(cfgs_t ,xmlNodeGetAttribute ( node, name ))
	end
	xmlSaveFile ( aja)
	xmlUnloadFile ( aja )
	if n ~= nil then
		callClient(  n, "updatePanel",cfgs_t)	
	--	outputChatBox('loading server: '..tostring(  getTickCount()-gowno ))
	else
	return cfgs_t
	end
end


function addPanelConfig(name)
local aja = xmlLoadFile ( ":"..getResourceName(getThisResource()).."/cfg/cfgs.xml" )
local node = xmlFindChild ( aja, "cfgs", 0 )
xmlNodeSetAttribute ( node, "cfg"..tostring(#getPanelConfigs()+1), name )
	xmlSaveFile ( aja)
	xmlUnloadFile ( aja )
end


function saveConfing(name,data)
local nowy = xmlLoadFile ( ":"..getResourceName(getThisResource()).."/cfg/"..tostring(name)..".xml")
local aja = nowy or xmlCreateFile  ( ":"..getResourceName(getThisResource()).."/cfg/"..tostring(name)..".xml","settings" )
local node = xmlFindChild ( aja, name, 0 ) or xmlCreateChild ( aja, name )
	for k,v in pairs(data) do
		if type(v) == "table" then
		v = toJSON( v)
		end
	xmlNodeSetAttribute ( node,k,v)
	end
		xmlSaveFile ( aja)
		xmlUnloadFile ( aja )
		if nowy == false then
		addPanelConfig(name)
		end
	locadConfing(name)	
end

function desroyConfing(name)

fileDelete ( ":"..getResourceName(getThisResource()).."/cfg/"..tostring(name)..".xml")

	locadConfing(name)	
end

function locadConfing(name,player)
local gowno = getTickCount()
cfg_file = name
local aja = xmlLoadFile ( ":"..getResourceName(getThisResource()).."/cfg/"..tostring(name)..".xml") 
local node = xmlFindChild ( aja, name, 0 )
local att =  xmlNodeGetAttributes ( node )
local data_t = {}
	for name,value in pairs ( att ) do
		local d = tostring(xmlNodeGetAttribute ( node, name ))
		if string.find(name,"grid_")  then
		d = fromJSON ( d )
		end
		data_t[name] = d
	--	table.insert(data_t,d)
		--outputServerLog  ( 	xmlNodeGetAttribute ( node, name ))
	end
		xmlUnloadFile ( aja )
		loadGameSettings(data_t)	
		set(""..getResourceName(getThisResource()).."._@cfg",name)
		if player ~= nil then
		callClient(  player, "locadClientConfing",data_t)
		end
--outputChatBox('loading server: '..tostring(  getTickCount()-gowno ))		
end

function isNot(s)
local wrong = {
9, 10, 11, 12, 13, 31, 32, 33, 38, 39, 40, 41, 43, 44, 53, 54, 55, 56, 58, 
63, 64, 69, 75, 76, 77, 85, 87, 88, 89, 90, 91, 92, 93, 94, 95, 112, 129, 130, 
131, 132, 134, 136, 137, 138, 139, 140, 141, 145, 148, 150, 152, 157, 160, 162,
169, 172, 178, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 201, 207, 
209, 210, 211, 212, 214, 215, 216, 218, 219, 224, 225, 226, 229, 230, 231, 
232, 233, 234, 235, 236, 237, 238, 243, 244, 246, 251, 252, 253, 256, 257, 261, 263}
	for i=1,#wrong do
		if s == wrong[i] then
			return 0
		end
	end
	return s
end


local _core_fix 

	function _core_crouchBug()
		if game_settings.global[5] == 'alternative' then
		--	setGlitchEnabled ( "fastfire", true )
		--	setGlitchEnabled ( "crouchbug", false )
			
		--	setGlitchEnabled ( "fastfire", false )
		--	setGlitchEnabled ( "crouchbug", true )
			setGlitchEnabled ( "fastfire", true )
			setGlitchEnabled ( "crouchbug", true )	
		
		elseif game_settings.global[5] == 'on' then
		--	setGlitchEnabled ( "fastfire", false )
		--	setGlitchEnabled ( "crouchbug", false )	
		
			setGlitchEnabled ( "fastfire", true )
			setGlitchEnabled ( "crouchbug", true )	
		elseif game_settings.global[5] == 'default' then
		--	setGlitchEnabled ( "fastfire", true )
		--	setGlitchEnabled ( "crouchbug", false )
		
			setGlitchEnabled ( "fastfire", false )
			setGlitchEnabled ( "crouchbug", true )
		elseif game_settings.global[5] == 'off' then	
		--	setGlitchEnabled ( "fastfire", true )
		--	setGlitchEnabled ( "crouchbug", true )		
		
			setGlitchEnabled ( "fastfire", false )
			setGlitchEnabled ( "crouchbug", false )		
		end
		--[[	if game_settings.global[5] == 'alternative' then
				local k_ = {{24,0.5},{25,0.575},{33,0.63},{34,0.63},{30,0.65},{31,0.65},{29,0.65}}
				for k,v in pairs(k_) do
					local s = setWeaponProperty (v[1],"pro", "anim_breakout_time",v[2] )
					outputChatBox(tostring(v[1])..'  '..tostring(v[2]))
				end
			else]]
				--[[local k_ = {24,25,33,34,30,31}
				for i=1,6 do
					setWeaponProperty (k_[i],"pro", "anim_breakout_time",getOriginalWeaponProperty (k_[i], "pro","anim_breakout_time") )
				end]]
		--	end
			
	--	setWeaponProperty (31,'pro','damage',26)
	--	setWeaponProperty (24,'pro','accuracy',1.35)
		--setGlitchEnabled ( "quickreload", false )
		setGlitchEnabled ( "fastmove", true )
		setGlitchEnabled ( "highcloserangedamage", false )
		callClient( getRootElement(), "_core_crouchBug")
	end

	local c_modes = {alternative={true,true},off={false,false},default={false,true}}
	--_core_a_t ={ {"fastfire","crouchbug"},{"quickreload","fastmove","highcloserangedamage"} }
	_core_a_t ={ {"fastfire","crouchbug"},{"fastmove","highcloserangedamage"} }
	function _core_acbug()
		if  c_modes[game_settings.global[5]] then
			for k,v in ipairs(_core_a_t[1]) do
				if isGlitchEnabled ( v ) ~= c_modes[game_settings.global[5]][k] then
					setGlitchEnabled ( v, c_modes[game_settings.global[5]][k] )
				end
			end
		end
		for k,v in ipairs(_core_a_t[2]) do
			if isGlitchEnabled ( v ) == true then
				setGlitchEnabled ( v, false)
			end
		end
	end
	
	

function loadGameSettings(t,a)
	if getElementData ( sett,"Round" ) == 0 then
	--	outputChatBox('DEBUG: '..tostring( t.global['Anti Cheat'] ))
		if t.global['Anti Cheat']  == nil then
			t.global['Anti Cheat'] = 'simple'
		end
	--	outputChatBox('DEBUG: '..tostring( t.global['Anti Cheat'] ))
		game_settings.vehicles = t.vehicles
		game_settings.anticheat = {t.global['Anti Cheat']}
		game_settings.kickere = {math.max(25,tonumber(t.global['Minimal fps'])), math.min(550, tonumber(t.global['Maximal ping'])), math.min(10,tonumber(t.global['Maximal packet loss']) )}
		game_settings.skins = {isNot(tonumber(t.teams_l[1].Skin)),isNot(tonumber(t.teams_l[2].Skin)),227}
		game_settings.global = {t.global['Anti Helli Kill'],t.global['Anti Car Kill'],t.global['Enable Knife'],t.global['Hide Health'],t.global['Crouch Bug'],t.global['Auto Puase']}
			--	outputChatBox(' Co kurwa znowu? '..tostring( game_settings.global[5]))
		Wynik ={[team1] = game_settings.skins[1],[team2] = game_settings.skins[2],[team3] = game_settings.skins[3]}
		callClient(  getRootElement(), "loadGameSettings",game_settings)
		_core_crouchBug()	
		if game_settings.global[4] == 'true' and health_use == true then
			call(getResourceFromName(scoreboard_n), "removeScoreboardColumn", "Health")
			health_use = false
		elseif game_settings.global[4]  == 'false' and health_use == false then
			call(getResourceFromName(scoreboard_n), "addScoreboardColumn", "Health",getRootElement(),6,0.06)
			health_use = true
		end
		setTeamName(team1,tostring(t.teams_l[1].Name)) setTeamName(team2,tostring(t.teams_l[2].Name))
		game_settings.weapons = {}
		for k, v in pairs ( t.weapons ) do
			game_settings.weapons[tonumber(k)] = v
		end	
		
		team_colors = {[team3]="#999999",[false]="#FFFFFF"}
		local r,g,b = gettok (t.teams_l[1].Color, 1,44),gettok (t.teams_l[1].Color, 2, 44),gettok (t.teams_l[1].Color, 3, 44)
		setTeamColor(team1,r,g,b)
		team_colors[team1] = RGBToHex(tonumber(r),tonumber(g),tonumber(b))
		r,g,b = gettok (t.teams_l[2].Color, 1, 44),gettok (t.teams_l[2].Color, 2, 44),gettok (t.teams_l[2].Color, 3, 44)
		setTeamColor(team2,r,g,b)
		team_colors[team2] = RGBToHex(tonumber(r),tonumber(g),tonumber(b))
		roundtimers[1] = {tonumber( gettok (t.global['Base Time'], 1, string.byte(':'))),  tonumber( gettok (t.global['Base Time'], 2, string.byte(':'))) }
		roundtimers[2] = {tonumber( gettok (t.global['Arena Time'], 1, string.byte(':'))),  tonumber( gettok (t.global['Arena Time'], 2, string.byte(':'))) }
		setFPSLimit(tonumber(t.global['FPS Limit']) or getFPSLimit())
	--	outputChatBox('MODE: '..tostring( round_mode[1]) )
		if isTimer ( _core_a_t.timer ) == false then
			_core_a_t.timer = setTimer(_core_acbug ,500,0)
		end	
		if game_settings.anticheat[1] ~= "simple" then
		
		end
		
	else
		addEventHandler ( "Aspect:OnRoundEnds",getRootElement(), load_confing_fix )
	end	
end
addEvent ( "Aspect:OnRoundEnds")
function load_confing_fix()
	removeEventHandler ( "Aspect:OnRoundEnds", getRootElement(), load_confing_fix )
	_panel_load(false,get(""..getResourceName(getThisResource()).."._@cfg"))
end

function resend()
--"extreme"
end





function loadVehiclesToTable(t)
	local vehicles_list = {481,510,522,521,468,593,548,417,487,429,496,541,411,451,445,473,493,595,453,446,454,573,400,505,403,413,440,596,437,431,560,443}
		for k,v in ipairs(vehicles_list) do
			if loadVehiclesToTable_(t,getVehicleNameFromModel ( v  )) == false then
				table.insert( game_settings.vehicles,getVehicleNameFromModel ( v  ))
			end
		end
	local vehicles_listbD = {425,520,577,447,430,601,464,432,407,544}	
	for k2,v2 in ipairs(vehicles_listbD) do
		vehicles_listbD[k2] = getVehicleNameFromModel ( v2 )
	end
		for k2,v2 in ipairs(game_settings.vehicles) do
			for k1,v1 in ipairs(vehicles_listbD) do
			--	outputServerLog(tostring(v2)..tostring(v1))
				if v2 == v1 then
				local c = table.remove( game_settings.vehicles, k2)
				--outputChatBox(' ?? '..tostring(c))
				--table.remove( vehicles_listb, k1)
				end
			end
		end
end

function loadVehiclesToTable_(t,v)
	for k1,v1 in ipairs(t) do
		if v == v1 then
			return true
		end
	end
	return false
end

function sync_on_start(gracz)
	callClient(  gracz, "loadGameSettings",game_settings)
	triggerEvent("onPlayerLogin",gracz)
	callClient( gracz, "_core_crouchBug")
end
function loadcfgtoGui(n)
	locadConfing( get(""..getResourceName(getThisResource()).."._@cfg"),n)
	--set ( "BaseMode._@cfg" var value )
end
function sync_weapons_settings(player)
	local p_w = {}
	for i=1,12 do
		local r = getPedTotalAmmo ( player, i )
			if r ~= 0 then
				table.insert (p_w,getPedWeapon ( player, i ))
			end
	end
	if #p_w > 0 then
		callClient(getRootElement(),'countWeaponLimits',p_w,getPlayerTeam(player),-1)
	end	
	callClient( player, "LoadWeponMenu",game_settings.weapons)
	--takeAllWeapons ( player )
end

logget_out = {}

addEventHandler("onPlayerLogin",getRootElement(),
  function()
	if IsPlayerAdmin(source) == true then
	logget_out[source] = true
	callClient(  source, "updatelogget_out",true)
	end
  end
)

function loggedOut()
	if logget_out[source] then
	logget_out[source] = nil
		callClient(  source, "updatelogget_out",nil)
	end
end
addEventHandler("onPlayerLogout",getRootElement(),loggedOut)

	function countDamage(player, attacker, loss )
		if loss ~= 0 and attacker and getElementType (attacker) == "player" and attacker ~= player then
			p_dmg[attacker] = math.round( (p_dmg[attacker]+loss) ,0)
		end
	end
	
	function onPlayerDamage_s ( attacker, weapon, bodypart, loss ) 
		countDamage(source, attacker, loss )
	end
	addEventHandler ( "onPlayerDamage", getRootElement (), onPlayerDamage_s )

-- register player_Wasted as a handler for onPlayerWasted

	function onPlayerWasted_s ( totalAmmo, killer, Weapon, bodypart  ) 
	--outputChatBox('debug: '..tostring(source)..' '..tostring(killer)..' '..tostring(getElementHealth(source)))
		countDamage(source, killer, getElementHealth(source) )
	end
	addEventHandler ( "onPlayerWasted", getRootElement(), onPlayerWasted_s )

	g_loading = tostring(getTickCount()-g_loading)
	
	
function playerConnect ()
local ver = getPlayerVersion(source)
local m_ver  =  string.gsub( tostring(string.sub(ver, 1,5)), ".", "a") 
local n_ver = string.sub(ver, 9,13)
--[[
outputChatBox(tostring(ver))
outputChatBox(tostring(m_ver))
outputChatBox(tostring(n_ver))
]]
end
 

addEventHandler ("onPlayerJoin", getRootElement(), playerConnect)




function checkAdminPanels()
local admin_r ={}
local group = aclGetGroup ( "Admin" )
     local resourceTable = getResources()
     for resourceKey, resourceValue in ipairs(resourceTable) do
		  
			if getResourceState ( resourceValue ) == 'running' then
				table.insert( admin_r,resourceValue )
			end
     end
	local text_return = ""
	  for k, v in ipairs(admin_r) do
			if "running" ==  getResourceState ( v ) then
			local name = getResourceName(v)
				if isObjectInACLGroup ( "resource." .. name, group ) == true then
					text_return = text_return.."\n * '".. name.."'".." ( Admin rights )"
					else
					text_return = text_return.."\n * '"..name.."'"
				end
			end
	 end
	 return text_return
end



function history_cmdclear(gracz)
	if getElementData ( sett,"Round" ) == 0 then
		if #history_data > 0 then
		
			history_data = {}
		end
			outputChatBox(  "#FF0000* #FFD700History has been cleared.",gracz, 255, 255, 255, true )
			outputChatBox ( "#FF0000** Info:#0AC419 Admin: #FF0000"..tostring(getPlayerName(gracz)).."#0AC419 reset history of playing rounds.", getRootElement(), 255, 255, 255, true )
	end		
end
addCommandHandler("clean",history_cmdclear)
addCommandHandler("resethistory",history_cmdclear)
addCommandHandler("clearhistory",history_cmdclear)





function callHelp(player)
	local team = getPlayerTeam( player )
	local x,y,z = getElementPosition( player )
	local sound = "sounds/hitassist.wav"
		if getElementHealth(player) > 92 then
			sound = "sounds/fireassis.wav"
		end
	callClient(  Team_parr[team], "playSound3DHelp",sound, x,y,z )
	if help_t[player] then
	--	setElementPosition(help_t[player]["blip"], x,y,z)
		resetTimer ( help_timer[player] )
	else
		local r,g,b = getTeamColor(team)
		help_t[player] = {
		["blip"] = createBlipAttachedTo ( player, 0, 3, r -(g/3),g,(b+r/4), 255, 0 , 1500,  Team_parr[team] ),
	--	["blip2"] = createBlipAttachedTo ( player, 0, 1, r,g,b, 255, 0 , 1500,  Team_parr[team] ),
		["arrow"] = createMarker (  x,y,z, "arrow", 0.5, r,g,b , 200,  Team_parr[team]  )}
		 attachElements ( help_t[player]["arrow"], player, 0,0, 1.5 )
		help_timer[player]  = setTimer(destoyCallHelp,30000,1,player)
	end
	outputChatBox(  "#FF0000** [HELP]:#0AC419 Team mate:#C0C0C0 "..tostring( getPlayerName( player) ).."#0AC419 needs help! Go to #C0C0C0point#0AC419 marked on the radar!",Team_parr[team] , 255, 255, 255, true )
end

function destoyCallHelp(player)
		destroyElement(help_t[player]["blip"])
	--	destroyElement(help_t[player]["blip2"])
		destroyElement(help_t[player]["arrow"])
		help_t[player] = nil
		help_timer[player] = nil
end


function onChat ( message, messageType )
	if messageType == 0 then
		cancelEvent()
		if chat_s == true then
			for i = 1,string.len(message) do
				local b = string.byte(message,i) 
					if b < 32 or b > 126 then
						outputChatBox ( "#FF0000Error: #00FF00Illegal characters on global chat, use ENGLISH chars or write on TEAMCHAT (#FF0000 Y#00FF00 ).", source, 255, 255, 255, true )
						return false
					end
			end
		end	
		local team = getPlayerTeam(source)
		local color = team_colors[team]
		outputChatBox ( "( ".. getElementData ( source,"ID" ).." ) ".. color .. getPlayerName ( source ) .." : #E0D0B0" .. message, getRootElement(), 224, 208, 176, true )
	elseif messageType == 2 then
		local team = getPlayerTeam(source)
		local color = team_colors[team]
		outputChatBox ( "( ".. getElementData ( source,"ID" ).." ) ( TEAM ) ".. color .. getPlayerName ( source ) ..": #cab997" .. message,  Team_parr[team], 224, 208, 176, true )
		cancelEvent()	
	end
end
addEventHandler ( "onPlayerChat", getRootElement(), onChat )


function help_window(gracz)
	local version = getVersion ( )
	local d_send = {
	ver={version.tag,version.os,version.type},
	cfg=cfg_file,
	admins=checkAdminPanels(),
	fps=getFPSLimit(),
	}
	callClient(  gracz, "help_window",d_send,history_data,_core_cmds_c)
end

function restore_window(gracz,id)
	
	if restore_state == "off" then
		outputChatBox ( "#FF0000** Error:#0AC419 To use restore features you must enable it in 'other_settings.xml'.", gracz, 255, 255, 255, true )
	--	callClient(  gracz, "restore_window",{},false)
		return false
	end
	local p_t_r = getPlayerByID(tonumber(id))
	if p_t_r and getElementData ( p_t_r,"IsSpawned" ) == 1 then
		outputChatBox ( "#FF0000** Error:#0AC419 This player is actually in round.", gracz, 255, 255, 255, true )
	--	callClient(  gracz, "restore_window",{},false)
		return false
	end
	
	if p_t_r then
	--	outputChatBox(tostring(getPlayerTeam(p_t_r)))
		local send = executeSQLSelect ( "restore_", "name , time, reason, hp, pos", "team = '" .. tostring( getPlayerTeam(p_t_r) ) .. "'" )
		for k, v in pairs(send) do		
			send[k].pos = fromJSON( send[k].pos)
		end
	callClient(  gracz, "restore_window",send,p_t_r)
	end
end

function view_window(gracz,type)
	local list = {base={},arena={}}
     local resourceTable = getResources() 
     for k, v in ipairs(resourceTable) do
          local name = getResourceName(v)
			if string.find(name,"base") then
				table.insert(list["base"], name)
			elseif string.find(name,"arena") then	
				table.insert(list["arena"], name)
			end
     end
	callClient(  gracz, "view_windowLoad",list,type)
end
local lastmap = {}
local lastmapP = {}
function view_start(player,cmdname,nameS)
		if lastmap[1] then
			stopResource(lastmap[1])
		end
	
		local res_name = cmdname.."_"..nameS
		local root = getResourceFromName ( res_name )
		tr = root
		lastmap={root,res_name,nameS}
		 playerG  = player
		 lastmapP[playerG] = root
		if root_state == "running" then
			stopResource(root)
		end
		startResource(root)
	end
	
	
		function view_load( res )
		if res ~= getThisResource() then
			local name = tostring(getResourceName(res))
				if name == lastmap[2] then
					local	MapRootElement = getResourceRootElement(res)
					local int = get(name..".#interior") or 0
					local marker_o = getElementsByType ( "Central_Marker",MapRootElement ) 
					local marker_t = {getElementData(marker_o[1], "posX"),getElementData(marker_o[1], "posY"),getElementData(marker_o[1], "posZ")}
				
					local b_type = get("Aspect"..".#type")
					local type_b 
					if b_type then
						type_b = "Base "..lastmap[3].." type: ".. b_type 
					end	
					callClient(  playerG, "view_frecam",marker_t[1],marker_t[2],marker_t[3],int,type_b)
					--[[Dodac proste gui z mozliwoscia przyblizania, oddalania, obrotu, informacja o bazie
						Dodac pokazywanie miejsca gdzie jest marker]]
				end
		end		
	end	
	function stopYourResource(playerG)
		if lastmapP[playerG] then
			stopResource(lastmapP[playerG])
			lastmapP[playerG] = nil
		end
	
	end
	
addEventHandler ( "onResourceStart", getRootElement(), view_load ) 


	function _core_outofrange(player,x,y,z,r)
		if getPedOccupiedVehicle ( player ) then
			if getPedOccupiedVehicleSeat ( player ) == 0 then
				setElementInterior(player,0)
				setElementInterior(getPedOccupiedVehicle ( player ),0,x,y,z-300)
				setElementRotation( getPedOccupiedVehicle ( player ),r)
			else
				setElementInterior(player,0)
			end
		else
			setElementInterior(player,0,x,y,z)
			setElementRotation(player,r)
		end
	end


--///////////////////////////////////////////////////////////////


function pause_cmd(gracz)
	if IsPlayerAdmin(gracz) == false then 
		outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", gracz, 255, 255, 255, true )
		return
	end	
	if getElementData ( sett,"Round" ) == 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 Round hasn't actually started.", gracz, 255, 255, 255, true )
        return
	end
	if RoundPaue == true then
		play_cmd(gracz)
		--outputChatBox ( "#FF0000** Error:#0AC419 Round is actualy paused.", gracz, 255, 255, 255, true )
        return
	end
	setGameSpeed(0)
	callClient( getRootElement(), "PauseRound" )
	Roznica_s = getTickCount()
	RoundPaue = true
end
addCommandHandler( "pause",pause_cmd)

 cmd_play_sts = false
function play_cmd(gracz)
	if IsPlayerAdmin(gracz) == false then 
		outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", gracz, 255, 255, 255, true )
		return
	end	
	if getElementData ( sett,"Round" ) == 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 Round hasn't actually started.", gracz, 255, 255, 255, true )
        return
	end
	if RoundPaue == false then
		outputChatBox ( "#FF0000** Error:#0AC419 Round is actually repaused.", gracz, 255, 255, 255, true )
        return
	end
	if cmd_play_sts == true then
		outputChatBox ( "#FF0000** Error:#0AC419 wait to repaused(3s).", gracz, 255, 255, 255, true )
        return
	end
	cmd_play_sts = true
	callClient( getRootElement(), "PreRePauseRound" )
			setTimer(function()
			--callClient( getRootElement(), "RePauseRound" )
			RoundPaue = false
			local Roznica_e = getTickCount()
			getTickEnd_c = getTickEnd_c+(Roznica_e - Roznica_s)
			cmd_play_sts = false
			setGameSpeed(1)
			end,2000,1)
	
end
addCommandHandler( "play",play_cmd)

function bm_GiveTheWepons(thisplayer, ar1,ar2,ar3,granade)
--[[
	local p_w = {}
	for i=1,12 do
		local r = getPedTotalAmmo ( thisplayer, i )
			if r ~= 0 then
				table.insert (p_w,getPedWeapon ( thisplayer, i ))
			end
	end
	if #p_w > 0 then
		callClient(getRootElement(),'countWeaponLimits',p_w,getPlayerTeam(thisplayer),-1)
	end	]]
takeAllWeapons ( thisplayer )
local w_limits = {}
	for k1,v1 in pairs(game_settings.weapons) do
	local stat = getWeaponStatById(k1)
		if stat ~= false then
			setPedStat ( thisplayer, stat, v1.Skills)
		end
	end
local a = {getRealAmmo(game_settings.weapons[ar1]),getRealAmmo(game_settings.weapons[ar2] ), getRealAmmo(game_settings.weapons[ar3])} 
	if ar1 == 16 and granade_use[thisplayer] and granade == 0 then
		giveWeapon ( thisplayer,  ar1 ,  0  )
	else	
		giveWeapon ( thisplayer,  ar1 ,  a[1] )
		if tonumber(game_settings.weapons[ar1]['Weapon limit per team']) > 0 then	
			table.insert(w_limits,ar1)
		end
	end	
	if ar2 == 16 and granade_use[thisplayer] and granade == 0 then
		giveWeapon ( thisplayer, ar2 ,  0  )
	else	
		giveWeapon ( thisplayer,  ar2 ,  a[2] )
		if ar1 ~= ar2 and tonumber(game_settings.weapons[ar2]['Weapon limit per team']) > 0 then	
			table.insert(w_limits,ar2)
		end
	end	
	if ar3 == 16 and granade_use[thisplayer] and granade == 0 then
		giveWeapon ( thisplayer,  ar3 ,  0  )
	else	
		giveWeapon ( thisplayer, ar3 ,  a[3] )
		if ar1 ~= ar3 and ar2 ~= ar3 and tonumber(game_settings.weapons[ar3]['Weapon limit per team']) > 0 then	
			table.insert(w_limits,ar3)
		end
	end	
	granade_use[thisplayer]=true
	if game_settings.global[3] == 'true' then
		giveWeapon ( thisplayer, 4 , 1 )
		--if tonumber(game_settings.weapons[4]['Weapon limit per team']) > 0 then	
		--	table.insert(w_limits,4)
		--end
	end
	if #w_limits > 0 then
		callClient(getRootElement(),'countWeaponLimits',w_limits,getPlayerTeam(thisplayer),1)
	end	
triggerEvent( "BaseMode:onPlayerGotWeapons",thisplayer, ar1,ar2,ar3)
end
function bm_GiveTheVehicle(thisplayer, ar1,x,y,z,pRot)
		local veh = createVehicle ( ar1,x,y,z+1,0,0,pRot)
		setElementPosition(thisplayer,x,y,z)
		setElementFrozen(veh,true)
		setElementInterior(veh,0 )
		warpPedIntoVehicle( thisplayer,veh)
				setElementParent ( veh, attach_data )
				local r,g,b = getTeamColor( getPlayerTeam(thisplayer))
				setVehicleColor ( veh, r,g,b,0,0,0,r,g,b,0,0,0 )
		addVehicleUpgrade ( veh,  1010)
		local bl = createBlipAttachedTo ( veh, 0, 1, 150,150,150,190,0,3000,Team_parr[getTeamByType("Attack")] )
		setBlipOrdering (bl, -1 )
		setCameraTarget ( thisplayer )
end


addEventHandler ( "onResourceStop", getResourceRootElement(getThisResource()), 
    function ( resource )
	call(getResourceFromName(scoreboard_n), "removeScoreboardColumn", "ID")
    call(getResourceFromName(scoreboard_n), "removeScoreboardColumn", "FPS")
	call(getResourceFromName(scoreboard_n), "removeScoreboardColumn", "Health")
	call(getResourceFromName(scoreboard_n), "removeScoreboardColumn", "Kills")
	call(getResourceFromName(scoreboard_n), "removeScoreboardColumn", "Deaths")
	--call(getResourceFromName(scoreboard_n), "removeScoreboardColumn", "Resolution")
	--call(getResourceFromName(scoreboard_n), "removeScoreboardColumn", "Ratio")
	setServerConfigSetting ( 'bandwidth_reduction',b_red)
    end 
)



addEventHandler ( "onElementDataChange", getRootElement(), 
    function ( theName,theOldValue )
	if theName == "Active_Players" and round_mode[1] == 'base' then
		--[[if theOldValue < getElementData(source, "Active_Players" ) then
			loadWeaponSettings()
		end	]]
	elseif getElementType(source) == "player" and getElementData ( sett,"Round" ) ~= 0 then
		if theName == "Health" then
			local eTeam = getPlayerTeam(source)
			if eTeam then
			--UpdateTeamVar("Health",eTeam,"%.0f",0)
				local new = getElementData(source,"Health")
		--	outputChatBox("new:" ..tostring(new)) outputChatBox(tostring(theOldValue)) 
		
			if type(theOldValue) ~= "number" then theOldValue = 0 end
				if type(new) == "number" then 
						
					UpdateHealth(eTeam,new-theOldValue)
				end
			end
		end	
    end 
end	
)


function UpdateTeamVar(Var,Team,stringF,od)
	local TeamVar = 0
	local players = getPlayersInTeam ( Team)
		for k,v in ipairs(players) do
			if getElementData ( v,"IsSpawned" ) == 1 then
				local add = tonumber(getElementData(v,Var))
					if add then
						TeamVar = tonumber(getElementData(v,Var)) + TeamVar
					end	
			end 
		end	
		if TeamVar > od then
			setElementData ( Team,Var,string.format(stringF,TeamVar) )
		else
			removeElementData ( Team, Var)
		end
end	

function UpdateHealth(team,var)
	if type(var) == "number" then

		local health = getElementData(team,"Health")
		--if type == "add" then
		 setElementData(team,"Health",health +var)
	--	else then
		-- setElementData(team,"Health",health -var)
		--end
	end
end	


function ChangeTeamAllPpl()
	local t1 = getTeamByType("Attack")
	local t2 = getTeamByType("Defense")
	setElementData ( t1,"t_type", "Defense" )
	setElementData ( t2,"t_type", "Attack" )	
end


function ChangeTeamAllPpl_cmd(gracz)
	if IsPlayerAdmin(gracz) == false then 
		outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", gracz, 255, 255, 255, true )
		return
	end	
	if getElementData ( sett,"Round" ) ~= 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 Round has actually started.", gracz, 255, 255, 255, true )
        return
	end
	ChangeTeamAllPpl()
	--outputChatBox ( "#0AC419Done.", gracz, 255, 255, 255, true )
	outputChatBox ( "#25c700[INFO]:#ffae00 Admin: #f8bb39".. getPlayerName( gracz ) .."#ffae00 swapped teams.", getRootElement(), 255, 255, 255, true )
end
addCommandHandler( "change_team_all",ChangeTeamAllPpl_cmd)	
addCommandHandler( "swap",ChangeTeamAllPpl_cmd)	







function tpto(gracz,cmd,id1,id2)
	if IsPlayerAdmin(gracz) == false then 
		outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", gracz, 255, 255, 255, true )
		return
	end	
	if getElementData ( sett,"Round" ) == 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 Round hasn't actually started.", gracz, 255, 255, 255, true )
        return
	end
	if id1 == id2 then
		outputChatBox ( "#FF0000** Error:#0AC419 Ids are the same.", gracz, 255, 255, 255, true )
        return
	end
	local graczfi = {getPlayerByID(tonumber(id1)),getPlayerByID(tonumber(id2))}
	for i=1,2 do
		if not graczfi[i] then
			outputChatBox ( "#FF0000** Error:#0AC419 Bad player ID.", gracz, 255, 255, 255, true )
			return
		end
		if getElementData ( graczfi[i],"IsSpawned" ) == 0 then
			outputChatBox ( "#FF0000** Error:#0AC419 This player is not spawned.", gracz, 255, 255, 255, true )
			return
		end
		local pT = getPlayerTeam(graczfi[i])
		if pT == false then
			outputChatBox ( "#FF0000** Error:#0AC419 This player didn't choose team.", gracz, 255, 255, 255, true )
			return
		end
	end	
	if isPedInVehicle ( graczfi[1] ) then
		removePedFromVehicle ( graczfi[1]  )
	end
	outputChatBox ( "#FF0000** Info:#0AC419 Player: #FF0000"..tostring(getPlayerName(graczfi[1])).."#0AC419 has been teleported to player: #FF0000"..tostring(getPlayerName(graczfi[2])), getRootElement(), 255, 255, 255, true )
	if isPedInVehicle ( graczfi[2] ) then
		local sts = warpPedIntoVehicle (  graczfi[1], getPedOccupiedVehicle (graczfi[2] ) )
		if sts == true then
			return false
		end	
	end
	local x,y,z = getElementPosition(graczfi[2]) 
	local randxy = {-0.15,0.15}
	setElementPosition(graczfi[1],x+randxy[math.random(1,2)],y+randxy[math.random(1,2)],z)
	
end
addCommandHandler( "tp",tpto)	


function heal(gracz,cmd,id1)
	if IsPlayerAdmin(gracz) == false then 
		outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", gracz, 255, 255, 255, true )
		return
	end	
		if getElementData ( sett,"Round" ) == 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 Round hasn't actually started.", gracz, 255, 255, 255, true )
        return
	end
	local graczfi = getPlayerByID(tonumber(id1))
		if not graczfi then
			outputChatBox ( "#FF0000** Error:#0AC419 Bad player ID.", gracz, 255, 255, 255, true )
			return  false
		end
		if getElementData ( graczfi,"IsSpawned" ) == 0 then
			outputChatBox ( "#FF0000** Error:#0AC419 This player is not spawned.", gracz, 255, 255, 255, true )
			return  false
		end
		local pT = getPlayerTeam(graczfi)
		if pT == false then
			outputChatBox ( "#FF0000** Error:#0AC419 This player didn't choose team.", gracz, 255, 255, 255, true )
			return  false
		end
		outputChatBox ( "#FF0000** Info:#0AC419 Player: #FF0000"..tostring(getPlayerName(graczfi)).."#0AC419 has been healed. #FF0000( last hp:" ..math.round(getElementHealth(graczfi), 0).." ).", getRootElement(),255, 255, 255, true )
		setElementHealth( graczfi,100 )
end
addCommandHandler( "heal",heal)	

	function _pane_player_tab(g,name,player)
		local serial = getPlayerSerial(player)
		local ip = getPlayerIP(player)
		local ping = getPlayerPing(player)
		local version = getPlayerVersion(player)
		callClient(g,'_pane_player_tab',name,player,serial,ping,hp,version,ip)
	end

function healall(gracz,cmd)
	if IsPlayerAdmin(gracz) == false then 
		outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", gracz, 255, 255, 255, true )
		return  false
	end	
	if getElementData ( sett,"Round" ) == 0 then
		outputChatBox ( "#FF0000** Error:#0AC419 Round hasn't actually started.", gracz, 255, 255, 255, true )
        return  false
	end

		local players = getElementsByType('player')
		for k,v in ipairs(players) do
			if getElementData ( v,"IsSpawned" ) == 1 then
				setElementHealth( v,100 )
			end
		end	
		outputChatBox ( "#FF0000** Info:#0AC419 All players have been healed. #FF0000( by "..tostring(getPlayerName(gracz)).." ).", getRootElement(),255, 255, 255, true )
end
addCommandHandler( "healall",healall)	

function countDmg()
		for k,v in pairs(p_dmg) do
			if v ~= 0 then
				setElementData(k,"Damage",getElementData(k,"Damage")+v)
				p_dmg[k] = 0
			end
		end
end






	function verify(g,cmd)
		if IsPlayerAdmin(g) == false then 
			outputChatBox ( "#FF0000** Error:#0AC419 you are not admin.", g, 255, 255, 255, true )
			return false
		end	
		if getElementData ( sett,"Round" ) == 0 then
			outputChatBox ( "#FF0000** Error:#0AC419 Round hasn't actually started.", g, 255, 255, 255, true )
			return false
		end	
		if game_settings.global[6] == 'false' then
			outputChatBox ( "#FF0000** Error:#0AC419 Option 'Auto Pause' isn't enabled and you can't use this command.", g, 255, 255, 255, true )
			return false
		end
		IsThisMomentToCheckWhoWon(getTeamByType("Attack"),getTeamByType("Defense"), getElementData ( sett,"Round" ),false,true)
		outputChatBox ( "#FF0000** INFO:#0AC419 Admin: #FF0000"..tostring(getPlayerName( g ) ).." #0AC419manually verified the round.", getRootElement(), 255, 255, 255, true )
	end
	addCommandHandler('verify',verify)
	
	function restore_update(name,time_,reason,hp,weapons,pos,veh,team_)
	--local result = executeSQLSelect ( "stats", "serial", "serial = '" .. serial .. "'" )
		--if ( type( result ) == "table" and #result == 0 ) or not result then 
			local a = executeSQLInsert ( "restore_", "'" ..name.. "','" ..time_.. "','" ..reason.. "', '" ..hp.. "', '" ..toJSON(weapons).. "', '" ..toJSON(pos).. "', '" ..toJSON(veh).. "', '" ..tostring(team_).. "'" )
		--else
		--	executeSQLUpdate ( "stats", "player = '"..nazwa .."'","serial = '" .. serial .. "'" )
		--end	
	end	
	
	function restore_restore(gracz,v,name)
			callClient( v, "_core_crouchBug")
			callClient( v, "RemoveSpectateMode",true )
			granade_use[v] = nil
			callClient( v, "replaceOnClientStart",LoadedMapInfo[2].."_"..LoadedMapInfo[3]  )
			callClient( v, "restore_fixes",1, true )
	local pT = getPlayerTeam(v)
	local ac = getElementData ( pT,"Active_Players")	 
			setElementData ( pT,"Active_Players",(ac+1)  )	 
				setElementData ( v,"IsSpawned", 1 )
					setElementData ( v, "Health",100 )
					local send = executeSQLSelect ( "restore_", "hp, weapons, pos, veh", "name = '" .. name  .. "'" )		
					local spawn_ = fromJSON ( send[1].pos )
				--	 setPedAnimation( v)
					spawnPlayer ( v, spawn_[1] , spawn_[2], spawn_[3]+1, math.random(0,360), Wynik[pT],getElementData(sett,"m_interior")  )
					setCameraTarget ( v )
					setElementAlpha(v,255)
					callClient( v, "AddSpawnProtect",1 )
					if getElementData ( sett,"_g_spwn_prot") == true then
						callClient( v, "_core_protect_s",true,'Spawn Protect: Enabled','"You\'re immortal!"' )
						--_core_protect_s(true,'Spawn Protect: Enabled','"You\'re immortal!"')
					end
				local r,g,b = getTeamColor(pT)
			setElementParent(v,Team_parr[pT])
		P_Blips[v] = createBlipAttachedTo ( v, 0, 1.75, r,g,b,150,0,3000,Team_parr[pT] )
		for k1,v1 in pairs(game_settings.weapons) do
		local stat = getWeaponStatById(k1)
			if stat ~= false then
				setPedStat ( v, stat, v1.Skills)
			end
		end
		local wep_ = fromJSON  (send[1].weapons )
		for k,i in pairs(wep_) do
			giveWeapon ( v, i[1] , i[2], true )
		end
		local veh_t = fromJSON  ( send[1].veh )
		if veh_t.v_d ~= false then
			local veh = getVehicleViaUserData(veh_t.v_d)
			---
			--- Nie zapisuje pojazdu
				if veh ~= false then
				setElementFrozen(veh,false ) 
				if getVehicleOccupant ( veh,0 ) == false then
					setElementPosition(veh,veh_t[1],veh_t[2],veh_t[3])
					if type(veh_t.vel) == 'table' then
						setElementVelocity(veh,unpack( veh_t.vel ))
					end
				end
				setTimer(warpPedIntoVehicle,500,1,v,veh)
					
				end
		end
		outputChatBox ( "#FF0000** INFO:#0AC419 The player ".. getPlayerName(v) .." has been restored successfully.", gracz, 255, 255, 255, true )
	end
	
	function getVehicleViaUserData(s)
		for k,v in pairs(getElementsByType ( "vehicle" )) do
		outputChatBox(tostring( v).." : "..tostring( s ) ) 
			if tostring(v) == s then
				return v 
			end
			return false
		end
	end
	
	
	function restore_fixes(v)
		local pT = getPlayerTeam(v)
		local spawn_t = getElementsByType ( spawn_types[pT],MapRootElement)
		
		callClient( v, "restore_fixes",2, {getElementData(spawn_t[1], "posX"),getElementData(spawn_t[1], "posY"),getElementData(spawn_t[1], "posZ")} )
	end
	
	 onResourceStart( getThisResource())	
	 
	 
	 
	
